@parity/product-sdk-host
Detect and talk to the Polkadot Desktop/Mobile host container.
Use isInsideContainer to branch behavior when running embedded vs. standalone,
and getHostLocalStorage, getHostProvider, and getStatementStore to reach
the storage, signer, and statement-store APIs the host injects.
npm install @parity/product-sdk-hostExports
Classes
| Name | Summary |
|---|---|
ChainNotSupportedError | Thrown by getHostProvider when the host container is reachable but does |
HostCallFailedError | A host call reached the container but failed on the Err channel. Wraps the |
HostError | Base class for all host errors. Use instanceof HostError (or isHostError) |
HostUnavailableError | The host API is not available — the app is running outside a Polkadot host |
Functions
| Name | Summary |
|---|---|
broadcastTransaction() | Broadcast a signed transaction to the network via the host. |
createHostLocalStorage() | Construct a host-backed HostLocalStorage instance. Retained for API |
createHostPreimageManager() | Construct a PreimageManager. Retained for API compatibility; with the single |
createProofAuthorized() | Have the host sign a Statement using the product’s allowance-bearing account, |
deriveEntropy() | Derive deterministic entropy from a context key (RFC-0007). |
err() | Create a failed Result. |
featureSupported() | Probe the host for support of a specific feature. |
formatHostError() | Extract a human-readable message from a host-side error. |
fromHex() | Convert a hex string (with or without 0x) to bytes. |
getAccountsProvider() | Get the accounts provider for managing host accounts, backed by |
getChainSpec() | Fetch a chain’s full spec (genesis hash, name, and properties) from the host |
getChatManager() | Get the host chat manager, backed by truApi.chat.*. Returns null when |
getHostLocalStorage() | Get the Host API localStorage instance when running inside a container. |
getHostProvider() | Get a PAPI-compatible JSON-RPC provider that routes through the host connection. |
getNotificationManager() | Get the host notification manager, backed by truApi.notifications.*. |
getPaymentManager() | Get the host payment manager, backed by truApi.payment.*. Returns null |
getPreimageManager() | Get the preimage manager for bulletin chain operations. |
getStatementStore() | Get the host statement store when running inside a container, backed by |
getThemeProvider() | Get the host theme provider, backed by truApi.theme.*. Returns null when |
getTruApi() | Get the TruAPI client for direct low-level access to host protocol domains. |
isChainSupported() | Convenience probe: is the chain with the given genesis hash supported by the |
isHostError() | Check whether a value is any HostError. |
isInsideContainer() | Detect if running inside a Host container (Polkadot Browser / Polkadot Desktop). |
isInsideContainerSync() | Detect whether the app is running inside a TrUAPI host container: an iframe |
navigateTo() | Ask the host to navigate to a URL (deep link or external link). |
ok() | Create a successful Result. |
requestDevicePermission() | Request a single device permission (camera, microphone, etc.) from the |
requestPermission() | Request a single remote permission from the host. |
requestResourceAllocation() | Request the host to pre-allocate one or more resource allowances. |
stopTransaction() | Stop an in-flight broadcast started by broadcastTransaction. |
toHex() | Convert bytes to a 0x-prefixed lower-case hex string. |
Interfaces
| Name | Summary |
|---|---|
AccountsProvider | Accounts provider handle, backed by truApi.account.* / truApi.signing.*. |
ChainProperties | Chain SS58/token properties as reported by the host’s |
ChainSpec | Combined chain-spec view returned by getChainSpec. |
ChatManager | Chat manager handle. Exposes room/bot registration, message sending, and |
ChatRoom | A chat room the product participates in. |
HostLocalStorage | Persistent storage exposed by the host container, including string, JSON |
HostPaymentBalanceSubscribeItem | Current payment balance state pushed to subscribers. |
HostStatementStore | Statement Store handle exposed by the host container, backed by |
HostSubscription | Subscription handle returned by the host. Exposes unsubscribe() plus an |
NotificationManager | Host notification manager handle. Exposes push(input) (resolves to a |
PaymentManager | Payment manager handle. Exposes balance subscription, top-up, payment |
PreimageManager | Preimage manager handle for bulletin chain operations, backed by |
ProductAccountId | Identifies a product-specific account by combining a dotNS domain name with a |
ResultAsync | Neverthrow-style ResultAsync returned by product-sdk methods. |
RingLocation | Locates a specific ring on a specific chain for ring VRF operations. |
SignedStatement | A statement with a required (not optional) proof. |
Statement | A statement with optional proof and metadata. |
ThemeProvider | Host theme provider handle. subscribeTheme(callback) receives a typed |
Type Aliases
| Name | Summary |
|---|---|
AllocatableResource | A resource the host can pre-allocate on behalf of the product (RFC 0010). |
AllocatableResource | A resource the host can pre-allocate on behalf of the product (RFC 0010). |
AllocationOutcome | Outcome of allocating a single resource (RFC 0010). |
AllocationOutcome | Outcome of allocating a single resource (RFC 0010). |
ChatBotRegistrationResult | Result of registering a bot ("New" | "Exists"). Re-exported from @parity/truapi. |
ChatMessageContent | Content of a chat message — one of several types. |
ChatMessageContent | Content of a chat message — one of several types. |
ChatReceivedAction | Action received via ChatManager.subscribeAction ({ roomId, peer, payload }). Re-exported from @parity/truapi. |
ChatRoom | — |
ChatRoomRegistrationResult | Result of registering a chat room ("New" | "Exists"). Re-exported from @parity/truapi. |
ContextualAlias | A contextual alias obtained from Ring VRF. |
DevicePermissionKind | Device permission the dapp can ask the host to grant via |
Feature | A feature the host can be probed for via featureSupported. |
HexString | Hex-encoded byte string, e.g. "0xdeadbeef". |
HostAccount | One of the user’s existing wallet accounts, surfaced through the host and |
HostErrorPayload | The structured error payload @parity/truapi surfaces on the Err channel of |
HostPaymentBalanceSubscribeItem | — |
HostPaymentStatusSubscribeItem | Payment lifecycle status pushed to subscribers. |
HostPaymentStatusSubscribeItem | Payment lifecycle status pushed to subscribers. |
NotificationId | Opaque identifier for a push notification, unique per product. |
NotificationId | Opaque identifier for a push notification, unique per product. |
PaymentTopUpSource | Source for a payment top-up operation. |
PaymentTopUpSource | Source for a payment top-up operation. |
ProductAccount | A product account — an app-scoped derived account managed by the host wallet. |
ProductAccountId | — |
PushNotificationError | Push notification error. |
PushNotificationError | Push notification error. |
PushNotificationInput | Push payload: text, an optional deeplink, and an optional scheduledAt |
RemotePermission | One remote-operation permission requested by the product (RFC 0002). |
RemotePermission | One remote-operation permission requested by the product (RFC 0002). |
RemotePermissionItem | Legacy alias of RemotePermission, kept for back-compat with code that |
Result | A value that is either a success (ok) carrying T, or a failure (err) carrying E. |
RingLocation | — |
SignedStatement | — |
Statement | — |
StatementProof | Cryptographic proof for a statement. |
StatementProof | Cryptographic proof for a statement. |
StatementsPage | A page of signed statements delivered by HostStatementStore.subscribe. |
StatementTopicFilter | Topic-based subscription filter. The host delivers statements that match |
ThemeMode | Host theme value. A { name, variant } struct re-exported from |
ThemeName | Identifies a named theme. |
ThemeName | Identifies a named theme. |
ThemeVariant | Light or dark variant. |
ThemeVariant | Light or dark variant. |
Topic | 32-byte statement topic. |
Topic | 32-byte statement topic. |
TruApi | The TruApi client — namespaced access to every host protocol domain |
Variables
| Name | Summary |
|---|---|
BULLETIN_RPCS | Bulletin Chain RPC endpoints per network environment. paseo and summit |
DEFAULT_BULLETIN_ENDPOINT | Default Bulletin Chain endpoint — the first entry under BULLETIN_RPCS.paseo. |
Classes
class ChainNotSupportedError
Thrown by getHostProvider when the host container is reachable but does
not support the requested chain — e.g. the chain isn’t enabled in this host
build, or the descriptor’s genesis hash has drifted from the host’s after a
network reset.
Surfacing this as a thrown error (rather than handing back a provider that
silently swallows every JSON-RPC request) is what lets callers of
createChainClient detect the failure. Without it, the host’s fallback no-op
provider drops every request on the floor and queries await forever.
Extends: Error
Constructors
constructor
new ChainNotSupportedError(genesisHash: string): ChainNotSupportedErrorProperties
genesisHash
stringGenesis hash of the chain the host refused, for programmatic detection.
class HostCallFailedError
A host call reached the container but failed on the Err channel. Wraps the
structured truapi HostErrorPayload as payload (also preserved
as cause); the message is rendered via formatHostError.
Extends: HostError
Constructors
constructor
new HostCallFailedError(label: string, payload: HostErrorPayload): HostCallFailedErrorProperties
payload
HostErrorPayloadclass HostError
Base class for all host errors. Use instanceof HostError (or isHostError)
to catch any host-related failure.
Extends: Error
Constructors
constructor
new HostError(message: string, options?: ErrorOptions): HostErrorclass HostUnavailableError
The host API is not available — the app is running outside a Polkadot host
container (no injected TruAPI transport). The dominant case during local
development. Branch with instanceof HostUnavailableError to surface an
“open this app in a Polkadot host” message.
Extends: HostError
Constructors
constructor
new HostUnavailableError(message: string = "Host API is not available"): HostUnavailableErrorFunctions
broadcastTransaction()
Broadcast a signed transaction to the network via the host.
Calls truApi.chain.broadcastTransaction and unwraps the response. The host
keeps re-broadcasting until the transaction is finalized/dropped or
stopTransaction is called with the returned operation id.
broadcastTransaction(genesisHash: `0x${string}`, transaction: `0x${string}`): Promise<Result<string | null, HostError>>Parameters
genesisHash: The0x-prefixed genesis hash of the target chain.transaction: The0x-prefixed SCALE-encoded signed transaction.
Returns
ok with the operation id to pass to stopTransaction (or
null if the host accepted the broadcast without issuing one), or
err(HostUnavailableError | HostCallFailedError).
Examples
import { broadcastTransaction, stopTransaction } from "@parity/product-sdk-host";
const r = await broadcastTransaction(genesisHash, signedTx);
// later, to stop re-broadcasting:
if (r.ok && r.value) await stopTransaction(genesisHash, r.value);createHostLocalStorage()
Construct a host-backed HostLocalStorage instance. Retained for API
compatibility; with the single cached TruAPI client this is equivalent to
getHostLocalStorage.
createHostLocalStorage(): Promise<HostLocalStorage | null>Returns
A HostLocalStorage instance, or null if unavailable.
createHostPreimageManager()
Construct a PreimageManager. Retained for API compatibility; with the single
cached TruAPI client this is equivalent to getPreimageManager.
createHostPreimageManager(): Promise<PreimageManager | null>Returns
A PreimageManager instance, or null if unavailable.
createProofAuthorized()
Have the host sign a Statement using the product’s allowance-bearing account, which it picks internally — RFC-10 §“Statement Store allowance”. No per-call account id is needed (this is the sponsored-submission path).
Pairs with getStatementStore’s submit: call this to obtain a proof,
attach it to the Statement, and submit the result.
createProofAuthorized(statement: Statement): Promise<Result<StatementProof, HostError>>Parameters
statement: The Statement to be signed.
Returns
ok with the proof to attach before submitting, or
err(HostUnavailableError | HostCallFailedError).
deriveEntropy()
Derive deterministic entropy from a context key (RFC-0007).
The host derives entropy from the user’s wallet + the provided context key. Calling with the same key on the same wallet yields the same bytes; different keys (or different wallets) yield uncorrelated entropy.
deriveEntropy(key: Uint8Array): Promise<Result<Uint8Array<ArrayBufferLike>, HostError>>Parameters
key: Context key bytes (typically a SCALE-encoded discriminator).
Returns
ok with the derived entropy bytes, or
err(HostUnavailableError | HostCallFailedError).
Examples
import { deriveEntropy } from "@parity/product-sdk-host";
const r = await deriveEntropy(new TextEncoder().encode("my-app:seed-v1"));
if (r.ok) { const seed = r.value; }err()
Create a failed Result.
err(error: E): Result<never, E>featureSupported()
Probe the host for support of a specific feature.
Calls truApi.system.featureSupported, unwraps the response, and returns the
host’s boolean answer.
featureSupported(feature: Feature): Promise<Result<boolean, HostError>>Parameters
feature: The feature to probe for.
Returns
ok(true) if the host supports the feature, ok(false) otherwise,
or err(HostUnavailableError | HostCallFailedError).
Examples
import { featureSupported } from "@parity/product-sdk-host";
const r = await featureSupported({ tag: "Chain", value: genesisHash });
if (r.ok && r.value) { ... }formatHostError()
Extract a human-readable message from a host-side error.
Renders the HostErrorPayload shapes @parity/truapi surfaces. Accepts
unknown because it is also the catch-all formatter for thrown adapter-method
Error messages, so it falls back to Error/string/JSON rendering for
anything that isn’t a recognized host error payload.
Used by HostCallFailedError to render its message, and by the throwing
adapter-method helper unwrapHostResult.
formatHostError(error: unknown): stringfromHex()
Convert a hex string (with or without 0x) to bytes.
fromHex(hex: string): Uint8ArraygetAccountsProvider()
Get the accounts provider for managing host accounts, backed by
truApi.account.* / truApi.signing.*. Returns null when running outside
a host container.
getAccountsProvider(): Promise<AccountsProvider | null>Returns
The accounts provider, or null if unavailable.
getChainSpec()
Fetch a chain’s full spec (genesis hash, name, and properties) from the host in one call.
Issues the three underlying chain.getSpec* requests concurrently, unwraps
each response, and parses the properties JSON. Note the genesisHash in the
result is the value the host echoes back from getSpecGenesisHash for the
looked-up chain — pass the chain’s known genesis hash as the lookup key.
null (outside a container) is preserved as an ok value — it is an
expected state, not a failure — so callers branch on r.ok && r.value. A
real host-call failure surfaces on the err channel.
getChainSpec(genesisHash: `0x${string}`): Promise<Result<ChainSpec | null, HostError>>Parameters
genesisHash: The0x-prefixed genesis hash identifying the chain.
Returns
ok(spec) with the combined ChainSpec, ok(null) if the
host is unavailable (running outside a container), or
err(HostCallFailedError) if any underlying host call fails.
Examples
import { getChainSpec } from "@parity/product-sdk-host";
const r = await getChainSpec(genesisHash);
if (r.ok && r.value) {
console.log(r.value.name, r.value.properties?.tokenSymbol);
}getChatManager()
Get the host chat manager, backed by truApi.chat.*. Returns null when
running outside a host container.
getChatManager(): Promise<ChatManager | null>Returns
The chat manager, or null if unavailable.
Examples
import { getChatManager } from "@parity/product-sdk-host";
const chat = await getChatManager();
if (chat) {
await chat.registerBot({ botId: "echo", name: "Echo Bot", icon: "" });
chat.subscribeAction((action) => { ... });
}getHostLocalStorage()
Get the Host API localStorage instance when running inside a container. Returns null outside a container or when the host transport is unavailable.
getHostLocalStorage(): Promise<HostLocalStorage | null>getHostProvider()
Get a PAPI-compatible JSON-RPC provider that routes through the host connection.
When running inside a Polkadot container, this builds a JsonRpcProvider over
truApi.chain.* (see module:papi-provider), enabling shared
connections and efficient routing. Returns null when not running inside a
container.
getHostProvider(genesisHash: `0x${string}`): Promise<JsonRpcProvider | null>Parameters
genesisHash: Genesis hash of the target chain (0x-prefixed hex string).
Returns
A host-routed JsonRpcProvider, or null if unavailable.
Throws
- When inside a container but the host can’t serve the chain — surfaced instead of returning a provider that would hang forever.
getNotificationManager()
Get the host notification manager, backed by truApi.notifications.*.
Returns null when running outside a host container.
getNotificationManager(): Promise<NotificationManager | null>Returns
The notification manager, or null if unavailable.
Examples
import { getNotificationManager, type PushNotificationError } from "@parity/product-sdk-host";
const notifications = await getNotificationManager();
if (notifications) {
try {
const id = await notifications.push({
text: "Doors open in 1h",
scheduledAt: someUnixMs,
});
// later: await notifications.cancel(id);
} catch (err) {
const cause = (err as Error).cause as PushNotificationError | undefined;
if (cause?.tag === "ScheduleLimitReached") {
// host hit its pending-notification cap — surface to the user
}
}
}getPaymentManager()
Get the host payment manager, backed by truApi.payment.*. Returns null
when running outside a host container.
getPaymentManager(): Promise<PaymentManager | null>Returns
The payment manager, or null if unavailable.
Examples
import { getPaymentManager } from "@parity/product-sdk-host";
const payments = await getPaymentManager();
if (payments) {
const sub = payments.subscribeBalance((b) => { ... });
await payments.topUp(1_000_000n, { tag: "ProductAccount", value: { derivationIndex: 0 } });
const { id } = await payments.requestPayment(500n, "0x…");
sub.unsubscribe();
}getPreimageManager()
Get the preimage manager for bulletin chain operations.
getPreimageManager(): Promise<PreimageManager | null>Returns
The preimage manager, or null if unavailable (outside a container).
getStatementStore()
Get the host statement store when running inside a container, backed by
truApi.statementStore.*.
Returns a store with subscribe, createProofAuthorized, and submit that
communicate through the host’s native binary protocol — bypassing JSON-RPC
entirely. Returns null outside a host container.
getStatementStore(): Promise<HostStatementStore | null>Returns
The host statement store, or null if unavailable.
getThemeProvider()
Get the host theme provider, backed by truApi.theme.*. Returns null when
running outside a host container.
getThemeProvider(): Promise<ThemeProvider | null>Returns
The theme provider, or null if unavailable.
Examples
import { getThemeProvider } from "@parity/product-sdk-host";
const provider = await getThemeProvider();
if (provider) {
const sub = provider.subscribeTheme((theme) => {
document.documentElement.dataset.theme = theme.variant.toLowerCase();
if (theme.name.tag === "Custom") loadCustomTheme(theme.name.value);
});
// sub.unsubscribe() to stop listening
}getTruApi()
Get the TruAPI client for direct low-level access to host protocol domains.
Returns the cached @parity/truapi client once the host transport is built
and the handshake has run, or null when running outside a container.
For most use cases, prefer the higher-level functions like
requestPermission, deriveEntropy, or getHostLocalStorage().
getTruApi(): Promise<TrUApiClient | null>Returns
The TruAPI client, or null if unavailable.
isChainSupported()
Convenience probe: is the chain with the given genesis hash supported by the
host? Wraps featureSupported for the Chain feature variant.
isChainSupported(genesisHash: `0x${string}`): Promise<Result<boolean, HostError>>Parameters
genesisHash: The chain’s0x-prefixed genesis hash.
Returns
ok(true) if the host supports the chain, ok(false) otherwise, or
err(HostUnavailableError | HostCallFailedError).
Examples
import { isChainSupported } from "@parity/product-sdk-host";
const r = await isChainSupported(genesisHash);
if (!r.ok || !r.value) {
tellUserChainUnavailable();
}isHostError()
Check whether a value is any HostError.
isHostError(error: unknown): error is HostErrorisInsideContainer()
Detect if running inside a Host container (Polkadot Browser / Polkadot Desktop).
The SDK is designed to run exclusively inside a host container. This function is primarily useful for early validation or informational purposes.
isInsideContainer(): Promise<boolean>isInsideContainerSync()
Detect whether the app is running inside a TrUAPI host container: an iframe (including a cross-origin parent), a marked webview, or a window carrying an injected host message port. Synchronous, so it can gate hot paths.
isInsideContainerSync(): booleannavigateTo()
Ask the host to navigate to a URL (deep link or external link).
Calls truApi.system.navigateTo and unwraps the response. The host resolves
the destination itself — a dot-suffixed deep link (e.g.
"https://search.dot") routes to another app/route inside the container, an
https:// URL opens externally.
navigateTo(url: string): Promise<Result<void, HostError>>Parameters
url: The URL to navigate to.
Returns
ok on success, or err: HostUnavailableError if the host
is unavailable, or HostCallFailedError if it denies the navigation
(NavigateToErr::PermissionDenied) or fails otherwise (NavigateToErr::Unknown).
Examples
import { navigateTo } from "@parity/product-sdk-host";
const r = await navigateTo("https://search.dot");
if (!r.ok) handle(r.error);ok()
Create a successful Result.
ok(value: T): Result<T, never>requestDevicePermission()
Request a single device permission (camera, microphone, etc.) from the host.
Calls truApi.permissions.requestDevicePermission and returns the host’s
boolean granted/denied outcome.
requestDevicePermission(permission: HostDevicePermissionRequest): Promise<Result<boolean, HostError>>Parameters
permission: The device permission to request.
Returns
ok(true) if the host granted the permission, ok(false) if denied,
or err(HostUnavailableError | HostCallFailedError).
Examples
const r = await requestDevicePermission("Camera");
if (!r.ok || !r.value) {
showCameraDeniedMessage();
}requestPermission()
Request a single remote permission from the host.
Calls truApi.permissions.requestRemotePermission and returns the host’s
boolean granted/denied outcome.
requestPermission(permission: RemotePermission): Promise<Result<boolean, HostError>>Parameters
permission: The remote permission to request.
Returns
ok(true) if the host granted the permission, ok(false) if denied,
or err(HostUnavailableError | HostCallFailedError).
Examples
const r = await requestPermission({ tag: "ChainSubmit", value: undefined });
if (!r.ok || !r.value) {
tellUserToReconnect();
}requestResourceAllocation()
Request the host to pre-allocate one or more resource allowances.
The host prompts the user once; subsequent operations covered by the granted allowance don’t re-prompt.
requestResourceAllocation(resources: AllocatableResource[]): Promise<Result<AllocationOutcome[], HostError>>Parameters
resources: Resources to request.
Returns
ok with per-resource outcomes in the same order as resources, or
err(HostUnavailableError | HostCallFailedError).
Examples
const r = await requestResourceAllocation([
{ tag: "BulletinAllowance", value: undefined },
]);
if (r.ok && r.value[0] === "Allocated") { ... }stopTransaction()
Stop an in-flight broadcast started by broadcastTransaction.
Calls truApi.chain.stopTransaction and unwraps the response.
stopTransaction(genesisHash: `0x${string}`, operationId: string): Promise<Result<void, HostError>>Parameters
genesisHash: The0x-prefixed genesis hash of the target chain.operationId: The operation id returned bybroadcastTransaction.
Returns
ok on success, or err(HostUnavailableError | HostCallFailedError).
Examples
await stopTransaction(genesisHash, operationId);toHex()
Convert bytes to a 0x-prefixed lower-case hex string.
toHex(bytes: Uint8Array): `0x${string}`Interfaces
interface AccountsProvider
Accounts provider handle, backed by truApi.account.* / truApi.signing.*.
Surfaces the user’s wallet accounts, app-scoped product accounts, Ring VRF,
user identity, connection status, and PolkadotSigner factories.
Lookup methods return a neverthrow ResultAsync (use .match(ok, err));
the signer factories return a synchronous PAPI PolkadotSigner.
Methods
createRingVRFProof
createRingVRFProof(dotNsIdentifier: string, derivationIndex: number, location: RingLocation, message: Uint8Array): ResultAsync<Uint8Array<ArrayBufferLike>, HostAccountCreateProofError>getLegacyAccounts
getLegacyAccounts(): ResultAsync<HostAccount[], HostAccountGetError>getLegacyAccountSigner
Build a PolkadotSigner for one of the user’s existing wallet accounts.
name is accepted for callsite ergonomics but unused — the signer is
derived from publicKey alone.
getLegacyAccountSigner(account: { name?: string; publicKey: Uint8Array }): PolkadotSignergetProductAccount
getProductAccount(dotNsIdentifier: string, derivationIndex?: number): ResultAsync<ProductAccount, HostAccountGetError>getProductAccountAlias
getProductAccountAlias(dotNsIdentifier: string, derivationIndex?: number): ResultAsync<ContextualAlias, HostAccountGetError>getProductAccountSigner
Build a PolkadotSigner for a product account. Signing routes through the
host’s createTransaction path: the host decodes the metadata and forwards
the opaque signed-extension bytes, so unknown extensions survive end-to-end.
getProductAccountSigner(account: ProductAccount): PolkadotSignergetUserId
getUserId(): ResultAsync<{ primaryUsername: string }, HostGetUserIdError>requestLogin
requestLogin(reason?: string): ResultAsync<HostRequestLoginResponse, HostRequestLoginError>subscribeAccountConnectionStatus
subscribeAccountConnectionStatus(callback: (status: HostAccountConnectionStatusSubscribeItem) => void): HostSubscriptioninterface ChainProperties
Chain SS58/token properties as reported by the host’s
chainSpecProperties call.
The host returns this as a JSON string (mirroring the substrate
chainSpec_v1_properties JSON-RPC, whose payload is an open-ended object).
getChainSpec parses it into ChainSpec.properties and also
surfaces the untouched JSON as ChainSpec.propertiesRaw. The well-known substrate fields are
typed for convenience; the index signature keeps any chain-specific extras
reachable without any at the call site.
Properties
ss58Format
numberAddress prefix used for SS58 encoding (e.g. 0 for Polkadot).
tokenDecimals
number | number[]Decimal places of the chain’s native token(s).
tokenSymbol
string | string[]Ticker symbol(s) of the chain’s native token(s).
interface ChainSpec
Combined chain-spec view returned by getChainSpec.
Properties
genesisHash
`0x${string}`The chain’s 0x-prefixed genesis hash, as reported by the host.
name
stringHuman-readable chain name (e.g. "Polkadot").
properties
ChainProperties | nullParsed chain properties, or null if the host’s JSON payload couldn’t
be parsed. Inspect propertiesRaw for the original string.
propertiesRaw
stringThe untouched JSON string the host returned for properties.
interface ChatManager
Chat manager handle. Exposes room/bot registration, message sending, and subscription to the room list and incoming actions.
Methods
registerBot
registerBot(request: HostChatRegisterBotRequest): Promise<ChatBotRegistrationStatus>registerRoom
registerRoom(request: HostChatCreateRoomRequest): Promise<ChatRoomRegistrationStatus>sendMessage
sendMessage(roomId: string, payload: ChatMessageContent): Promise<{ messageId: string }>subscribeAction
subscribeAction(callback: (action: HostChatActionSubscribeItem) => void): HostSubscriptionsubscribeChatList
subscribeChatList(callback: (rooms: ChatRoom[]) => void): HostSubscriptioninterface ChatRoom
A chat room the product participates in.
Properties
participatingAs
ChatRoomParticipationRoomHost or Bot.
roomId
stringRoom identifier.
interface HostLocalStorage
Persistent storage exposed by the host container, including string, JSON
and raw byte (readBytes/writeBytes) accessors. Most apps reach it
indirectly through the Storage package’s KvStore; reach for it directly
via getHostLocalStorage when you need raw host storage without the
KV abstraction.
Backed by truApi.localStorage.* (raw read/write/clear over hex bytes);
getHostLocalStorage adapts that into this richer surface. readString
resolves to "" for a missing key and readJSON/readBytes to
null/undefined.
Methods
clear
Remove a key.
clear(key: string): Promise<void>readBytes
Read raw bytes; undefined when the key is absent.
readBytes(key: string): Promise<Uint8Array<ArrayBufferLike> | undefined>readJSON
Read and JSON-parse a value; null when the key is absent.
readJSON(key: string): Promise<unknown>readString
Read a UTF-8 string value; "" when the key is absent.
readString(key: string): Promise<string>writeBytes
Write raw bytes.
writeBytes(key: string, value: Uint8Array): Promise<void>writeJSON
JSON-stringify and write a value.
writeJSON(key: string, value: unknown): Promise<void>writeString
Write a UTF-8 string value.
writeString(key: string, value: string): Promise<void>interface HostPaymentBalanceSubscribeItem
Current payment balance state pushed to subscribers.
See RFC 0006 .
Properties
available
bigintBalance that can be spent right now.
interface HostStatementStore
Statement Store handle exposed by the host container, backed by
truApi.statementStore.*. subscribe streams matching statements;
createProofAuthorized signs a statement with the product’s RFC-10 allowance
account (the sponsored path — no per-call account id); submit publishes a
signed statement. The statement-store package layers a higher-level client
on top.
Methods
createProofAuthorized
createProofAuthorized(statement: Statement): Promise<StatementProof>submit
submit(signedStatement: SignedStatement): Promise<void>subscribe
subscribe(filter: StatementTopicFilter, callback: (page: RemoteStatementStoreSubscribeItem) => void): HostSubscriptioninterface HostSubscription
Subscription handle returned by the host. Exposes unsubscribe() plus an
onInterrupt hook that fires if the host interrupts the subscription
server-side; onInterrupt returns a function that cancels the hook.
Methods
onInterrupt
onInterrupt(callback: (reason?: unknown) => void): () => voidunsubscribe
unsubscribe(): voidinterface NotificationManager
Host notification manager handle. Exposes push(input) (resolves to a
NotificationId) and cancel(id).
Methods
cancel
cancel(id: number): Promise<void>push
push(input: HostPushNotificationRequest): Promise<number>interface PaymentManager
Payment manager handle. Exposes balance subscription, top-up, payment requests, and payment-status subscription.
The balance / status / top-up-source shapes are @parity/truapi’s
HostPaymentBalanceSubscribeItem, HostPaymentStatusSubscribeItem, and
PaymentTopUpSource — used directly rather than re-aliased.
Methods
requestPayment
requestPayment(amount: bigint, destination: `0x${string}`, from?: number): Promise<{ id: string }>subscribeBalance
subscribeBalance(callback: (balance: HostPaymentBalanceSubscribeItem) => void, purse?: number): HostSubscriptionsubscribePaymentStatus
subscribePaymentStatus(paymentId: string, callback: (status: HostPaymentStatusSubscribeItem) => void): HostSubscriptiontopUp
topUp(amount: bigint, source: PaymentTopUpSource, into?: number): Promise<void>interface PreimageManager
Preimage manager handle for bulletin chain operations, backed by
truApi.preimage.*. lookup opens a HostSubscription (unsubscribe
onInterrupt) that delivers the preimage bytes — ornulluntil the host finds them;submituploads a preimage and resolves to its0x-prefixed hex key.
Methods
lookup
lookup(key: `0x${string}`, callback: (preimage: Uint8Array<ArrayBufferLike> | null) => void): HostSubscriptionsubmit
submit(value: Uint8Array): Promise<`0x${string}`>interface ProductAccountId
Identifies a product-specific account by combining a dotNS domain name with a derivation index.
Properties
derivationIndex
numberKey derivation index for generating product-specific accounts.
dotNsIdentifier
stringA dotNS domain name identifier (e.g., "my-product.dot").
interface ResultAsync
Neverthrow-style ResultAsync returned by product-sdk methods.
Use .match(onOk, onErr) to handle success/error cases.
Properties
match
(ok: (t: T) => A, err: (e: E) => B) => Promise<A | B>interface RingLocation
Locates a specific ring on a specific chain for ring VRF operations.
Properties
genesisHash
`0x${string}`Chain genesis hash.
hints
RingLocationHintOptional location hints.
ringRootHash
`0x${string}`Root hash of the ring.
interface SignedStatement
A statement with a required (not optional) proof.
Properties
channel
`0x${string}`Optional channel.
data
`0x${string}`Optional data payload.
decryptionKey
`0x${string}`Optional decryption key.
expiry
bigintOptional Unix timestamp expiry.
proof
StatementProofRequired cryptographic proof.
topics
`0x${string}`[][u8; 32] tags.
interface Statement
A statement with optional proof and metadata.
Properties
channel
`0x${string}`Optional channel.
data
`0x${string}`Optional data payload.
decryptionKey
`0x${string}`Optional decryption key.
expiry
bigintOptional Unix timestamp expiry.
proof
StatementProofOptional cryptographic proof.
topics
`0x${string}`[][u8; 32] tags.
interface ThemeProvider
Host theme provider handle. subscribeTheme(callback) receives a typed
ThemeMode on every change and returns a HostSubscription.
Methods
subscribeTheme
subscribeTheme(callback: (theme: HostThemeSubscribeItem) => void): HostSubscriptionType Aliases
type AllocatableResource
A resource the host can pre-allocate on behalf of the product (RFC 0010).
For the slot-table allowances (StatementStoreAllowance,
BulletinAllowance, SmartContractAllowance), pre-allocation is
opportunistic and the host may also fulfil the allowance implicitly on the
first submission. AutoSigning must be requested explicitly through this
call.
type AllocatableResource = Codec<AllocatableResource>type AllocatableResource
A resource the host can pre-allocate on behalf of the product (RFC 0010).
For the slot-table allowances (StatementStoreAllowance,
BulletinAllowance, SmartContractAllowance), pre-allocation is
opportunistic and the host may also fulfil the allowance implicitly on the
first submission. AutoSigning must be requested explicitly through this
call.
type AllocatableResource = { tag: "StatementStoreAllowance"; value?: undefined } | { tag: "BulletinAllowance"; value?: undefined } | { tag: "SmartContractAllowance"; value: number } | { tag: "AutoSigning"; value?: undefined }type AllocationOutcome
Outcome of allocating a single resource (RFC 0010).
type AllocationOutcome = Codec<AllocationOutcome>type AllocationOutcome
Outcome of allocating a single resource (RFC 0010).
type AllocationOutcome = "Allocated" | "Rejected" | "NotAvailable"type ChatBotRegistrationResult
Result of registering a bot ("New" | "Exists"). Re-exported from @parity/truapi.
type ChatBotRegistrationResult = ChatBotRegistrationStatustype ChatMessageContent
Content of a chat message — one of several types.
type ChatMessageContent = Codec<ChatMessageContent>type ChatMessageContent
Content of a chat message — one of several types.
type ChatMessageContent = { tag: "Text"; value: { text: string } } | { tag: "RichText"; value: ChatRichText } | { tag: "Actions"; value: ChatActions } | { tag: "File"; value: ChatFile } | { tag: "Reaction"; value: ChatReaction } | { tag: "ReactionRemoved"; value: ChatReaction } | { tag: "Custom"; value: ChatCustomMessage }type ChatReceivedAction
Action received via ChatManager.subscribeAction ({ roomId, peer, payload }). Re-exported from @parity/truapi.
type ChatReceivedAction = HostChatActionSubscribeItemtype ChatRoom
type ChatRoom = Codec<ChatRoom>type ChatRoomRegistrationResult
Result of registering a chat room ("New" | "Exists"). Re-exported from @parity/truapi.
type ChatRoomRegistrationResult = ChatRoomRegistrationStatustype ContextualAlias
A contextual alias obtained from Ring VRF.
Proves account membership in a ring without revealing which account.
Derived from @parity/truapi’s alias response, with both fields decoded to bytes.
type ContextualAlias = { [K in keyof WireAlias]: Uint8Array }type DevicePermissionKind
Device permission the dapp can ask the host to grant via
requestDevicePermission. A string union ("Camera", "Microphone",
…) re-exported from @parity/truapi.
type DevicePermissionKind = HostDevicePermissionRequesttype Feature
A feature the host can be probed for via featureSupported.
The only variant today is Chain, carrying the chain’s 0x-prefixed genesis
hash. This is a flattened form of truapi’s HostFeatureSupportedRequest,
which nests the hash as { tag: "Chain"; value: { genesisHash } } — we
inline value as the HexString for ergonomics and re-nest it at the call
site. New variants surface here as a widening of the union.
type Feature = unknowntype HexString
Hex-encoded byte string, e.g. "0xdeadbeef".
type HexString = `0x${string}`type HostAccount
One of the user’s existing wallet accounts, surfaced through the host and
identified by its public key and an optional name. Contrast with
ProductAccount, which is also user-controlled but derived by the
host for a specific app rather than picked from the user’s existing keys.
Derived from @parity/truapi’s LegacyAccount, with publicKey decoded to bytes.
type HostAccount = Omit<WireLegacyAccount, "publicKey"> & { publicKey: Uint8Array }type HostErrorPayload
The structured error payload @parity/truapi surfaces on the Err channel of
a host call, once unwrapped from the versioned wire envelope. Every host error
union is built from these:
- the catch-all
GenericError({ reason }), - a unit tagged variant (
{ tag }), or - a tagged variant carrying a reason (
{ tag, value: { reason } }).
GenericError is imported from @parity/truapi; the { tag } members are a
deliberate widening of truapi’s per-domain named variants (the formatter is
tag-agnostic). truapi has no umbrella error union to import today — once it
exports a canonical tagged-error union from codegen, replace these local
members with that import so the type is protocol-sourced rather than
hand-widened.
This is the payload the host public API carries inside a
HostCallFailedError on the err channel of its Result returns — not
the error type consumers branch on.
type HostErrorPayload = GenericError | { tag: string; value?: undefined } | { tag: string; value: { reason: string } }type HostPaymentBalanceSubscribeItem
type HostPaymentBalanceSubscribeItem = Codec<HostPaymentBalanceSubscribeItem>type HostPaymentStatusSubscribeItem
Payment lifecycle status pushed to subscribers.
Once a terminal state (Completed or Failed) is reached, the host
delivers it and may close the subscription.
See RFC 0006 .
type HostPaymentStatusSubscribeItem = Codec<HostPaymentStatusSubscribeItem>type HostPaymentStatusSubscribeItem
Payment lifecycle status pushed to subscribers.
Once a terminal state (Completed or Failed) is reached, the host
delivers it and may close the subscription.
See RFC 0006 .
type HostPaymentStatusSubscribeItem = { tag: "Processing"; value?: undefined } | { tag: "Completed"; value?: undefined } | { tag: "Failed"; value: { reason: string } }type NotificationId
Opaque identifier for a push notification, unique per product.
type NotificationId = Codec<number>type NotificationId
Opaque identifier for a push notification, unique per product.
type NotificationId = numbertype PaymentTopUpSource
Source for a payment top-up operation.
See RFC 0006 .
type PaymentTopUpSource = Codec<PaymentTopUpSource>type PaymentTopUpSource
Source for a payment top-up operation.
See RFC 0006 .
type PaymentTopUpSource = { tag: "ProductAccount"; value: { derivationIndex: number } } | { tag: "PrivateKey"; value: { sr25519SecretKey: HexString } } | { tag: "Coins"; value: { sr25519SecretKeys: HexString[] } }type ProductAccount
A product account — an app-scoped derived account managed by the host wallet.
The host derives a unique keypair for each app (identified by dotNsIdentifier)
so apps get their own account that the user controls but is scoped to the app.
Combines @parity/truapi’s ProductAccountId (the { dotNsIdentifier, derivationIndex } lookup key) with the ProductAccount payload, with
publicKey decoded to bytes.
type ProductAccount = ProductAccountId & Omit<WireProductAccount, "publicKey"> & { publicKey: Uint8Array }type ProductAccountId
type ProductAccountId = Codec<ProductAccountId>type PushNotificationError
Push notification error.
type PushNotificationError = Codec<HostPushNotificationError>type PushNotificationError
Push notification error.
type PushNotificationError = { tag: "ScheduleLimitReached"; value?: undefined } | { tag: "Unknown"; value: { reason: string } }type PushNotificationInput
Push payload: text, an optional deeplink, and an optional scheduledAt
(Unix timestamp in milliseconds; omit for immediate delivery). Re-exported
from the truapi wire request type so the shape stays in lockstep with the
protocol.
type PushNotificationInput = HostPushNotificationRequesttype RemotePermission
One remote-operation permission requested by the product (RFC 0002).
ChainSubmit, PreimageSubmit, and StatementSubmit are also triggered
implicitly by the corresponding business calls when not yet granted.
type RemotePermission = Codec<RemotePermission>type RemotePermission
One remote-operation permission requested by the product (RFC 0002).
ChainSubmit, PreimageSubmit, and StatementSubmit are also triggered
implicitly by the corresponding business calls when not yet granted.
type RemotePermission = { tag: "Remote"; value: { domains: string[] } } | { tag: "WebRtc"; value?: undefined } | { tag: "ChainSubmit"; value?: undefined } | { tag: "PreimageSubmit"; value?: undefined } | { tag: "StatementSubmit"; value?: undefined }type RemotePermissionItem
Legacy alias of RemotePermission, kept for back-compat with code that
used the older name. Use either freely.
type RemotePermissionItem = RemotePermissiontype Result
A value that is either a success (ok) carrying T, or a failure (err) carrying E.
type Result = { ok: true; value: T } | { error: E; ok: false }type RingLocation
type RingLocation = Codec<RingLocation>type SignedStatement
type SignedStatement = Codec<SignedStatement>type Statement
type Statement = Codec<Statement>type StatementProof
Cryptographic proof for a statement.
type StatementProof = Codec<StatementProof>type StatementProof
Cryptographic proof for a statement.
type StatementProof = { tag: "Sr25519"; value: { signature: HexString; signer: HexString } } | { tag: "Ed25519"; value: { signature: HexString; signer: HexString } } | { tag: "Ecdsa"; value: { signature: HexString; signer: HexString } } | { tag: "OnChain"; value: { blockHash: HexString; event: bigint; who: HexString } }type StatementsPage
A page of signed statements delivered by HostStatementStore.subscribe.
truapi’s RemoteStatementStoreSubscribeItem, re-exported under a friendlier
name. Pages arrive sequentially; isComplete is false while the host
streams the historical backfill and true once it’s done (and on every
subsequent live-update page).
type StatementsPage = RemoteStatementStoreSubscribeItemtype StatementTopicFilter
Topic-based subscription filter. The host delivers statements that match
either all of the listed topics (matchAll) or any of them (matchAny).
This is a field-discriminated form of truapi’s RemoteStatementStoreSubscribeRequest,
which is a tagged union ({ tag: "MatchAll"; value: Topic[] } | { tag: "MatchAny"; value: Topic[] }).
The transport maps between the two.
type StatementTopicFilter = { matchAll: Topic[] } | { matchAny: Topic[] }type ThemeMode
Host theme value. A { name, variant } struct re-exported from
@parity/truapi.
type ThemeMode = HostThemeSubscribeItemtype ThemeName
Identifies a named theme.
type ThemeName = Codec<ThemeName>type ThemeName
Identifies a named theme.
type ThemeName = { tag: "Custom"; value: string } | { tag: "Default"; value?: undefined }type ThemeVariant
Light or dark variant.
type ThemeVariant = Codec<ThemeVariant>type ThemeVariant
Light or dark variant.
type ThemeVariant = "Light" | "Dark"type Topic
32-byte statement topic.
type Topic = Codec<`0x${string}`>type Topic
32-byte statement topic.
type Topic = HexStringtype TruApi
The TruApi client — namespaced access to every host protocol domain
(permissions, entropy, signing, statementStore, system,
localStorage, …). Identical to TrUApiClient from @parity/truapi.
type TruApi = TrUApiClientExamples
const truApi = await getTruApi();
if (truApi) {
await truApi.permissions.requestRemotePermission({
permission: { tag: "ChainSubmit", value: undefined },
});
await truApi.system.navigateTo({ url: "polkadot://settings" });
}Variables
BULLETIN_RPCS
Bulletin Chain RPC endpoints per network environment. paseo and summit
are populated today; polkadot and kusama are reserved for when those
Bulletin deployments go live.
let BULLETIN_RPCS: { readonly kusama: string[]; readonly paseo: readonly ["wss://paseo-bulletin-next-rpc.polkadot.io"]; readonly polkadot: string[]; readonly summit: readonly ["wss://summit-bulletin-rpc.polkadot.io"] } = ...DEFAULT_BULLETIN_ENDPOINT
Default Bulletin Chain endpoint — the first entry under BULLETIN_RPCS.paseo.
let DEFAULT_BULLETIN_ENDPOINT: string = ...