Skip to Content
API ReferencehostOverview

@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-host

Exports

Classes

NameSummary
ChainNotSupportedErrorThrown by getHostProvider when the host container is reachable but does
HostCallFailedErrorA host call reached the container but failed on the Err channel. Wraps the
HostErrorBase class for all host errors. Use instanceof HostError (or isHostError)
HostResponseDecodeErrorA host call could not be processed to completion: the ResultAsync the
HostTimeoutErrorA host call got no answer before the truapi client’s deadline. The client
HostUnavailableErrorThe host API is not available — the app is running outside a Polkadot host

Functions

NameSummary
asProductId()Designate a product identifier without changing or validating its value.
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
createHostTxCreator()Build a creator that signs through sendToHost.
createProofAuthorized()Have the host sign a Statement using the product’s allowance-bearing account,
deriveEntropy()Derive deterministic entropy from a context key (RFC-0007).
deriveRefundIdempotencyKey()Returns the idempotency key to pass to observeOperationStatus for the
deriveRevokeIdempotencyKey()Returns the idempotency key to pass to observeOperationStatus for the
featureSupported()Probe the host for support of a specific feature.
findRingVrfKeyHandle()Select a registered key by its declared ring and return its opaque handle.
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
getHostChainInfo()Resolve chain roles against the current host.
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.
getLocaleProvider()Get the host locale provider, backed by truApi.locale.*. Returns null
getNftPurseManager()Returns the NFT purse manager, or null outside a host. On a host that has
getNotificationManager()Get the host notification manager, backed by truApi.notifications.*.
getPaymentManager()Get the host payment manager, backed by truApi.payment.*. Returns null
getPocketManager()Get the host Pocket manager. Returns null when running outside a host
getPreimageManager()Get the preimage manager for bulletin chain operations.
getRendererManager()Get the renderer manager, for drawing a body the SDK has no wrapper for.
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.
hostErrorName()Returns the name of the host’s error, for example OperationExists or
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()Host-container detection. true when a test client is injected, otherwise the
isNftPurseOperationFinished()Returns true when an operation is finished. Cleared means every NFT moved
navigateTo()Ask the host to navigate to a URL (deep link or external link).
newPaymentId()A fresh random 32-byte id for a top-up or payment request.
registerRenderContext()Claim one render context on this client.
renderFailure()Build the reason, so a refusal reaches the host instead of dying here.
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.
subscribeConnectionStatus()Subscribe to host-channel connection status. The callback fires synchronously
toHex()Convert bytes to a 0x-prefixed lower-case hex string.

Interfaces

NameSummary
AccountsProviderAccounts provider handle, backed by truApi.account.* / truApi.signing.*.
CardDrawRegistrationHandle for one card’s registration.
ChainPropertiesChain SS58/token properties as reported by the host’s
ChainSpecCombined chain-spec view returned by getChainSpec.
ChatCustomMessageRenderingRegistrationRegistration returned by the custom-message renderer channel.
ChatCustomMessageRenderingRequestRequest delivered when the host needs a native tree for a stored custom message.
ChatManagerChat manager handle. Exposes room/bot registration, message sending, and
ChatRoomA chat room the product participates in.
ChatSendMessageOptionsOptions for ChatManager.sendMessage.
HostChainDiscoveryThe host’s configured environment plus per-identifier resolved genesis hashes.
HostLocalStoragePersistent storage exposed by the host container, including string, JSON
HostNftPurseCreateChequeRequestRequest to hand items off in a cheque.
HostNftPurseCreateItemsRequestRequest to create new item keys in a purse.
HostNftPurseCreatePurseRequestRequest to create a purse owned by the caller.
HostNftPurseCreateReceiveKeyRequestRequest for a one-time receive key.
HostNftPurseDepositRequestRequest to deposit a received cheque.
HostNftPurseListenOneTimePaymentRequestRequest to wait for a cheque sent to a receive key.
HostNftPurseListenPaymentInboxRequestRequest to listen to one of the caller’s payment inboxes.
HostNftPurseListPursesRequestRequest to list an owner’s purses.
HostNftPurseObserveOperationStatusRequestRequest for the status of an operation the calling product registered.
HostNftPurseQueryPurseRequestRequest for one page of a purse’s spendable items.
HostNftPurseRebalancePurseRequestRequest to move items between purses.
HostNftPurseRefundRequestRequest to return a deposited cheque’s items to their original keys.
HostNftPurseRefundResponseThe refund’s moves, by the depositing purse’s item keys.
HostNftPurseRevokeChequeRequestRequest to release the items of an undelivered cheque.
HostNftPurseTransferItemRequestRequest to move one item to a key outside the purses.
HostPaymentBalanceSubscribeItemCurrent payment balance state pushed to subscribers.
HostSignerOptionsTransaction settings for host-backed signers.
HostStatementStoreStatement Store handle exposed by the host container, backed by
HostSubscriptionSubscription handle returned by the host. Exposes unsubscribe() plus an
HostTxExtensionOne extension as the host signs it.
HostTxRequestWhat the host needs to build and sign one transaction.
LocaleProviderHost locale provider handle. subscribeLocale(callback) receives a typed
NftPurseChequeItems handed off to a recipient.
NftPurseClearedItemOne item an operation moved.
NftPurseClearingReferenceProduct-visible clearing reference.
NftPurseInfoPageOne page of the spendable items of a purse.
NftPurseManagerThe NFT purse calls of the host. A call that fails throws an Error with the
NftPursePurseA purse as list_purses reports it.
NotificationManagerHost notification manager handle. Exposes push(input) (resolves to a
PaymentManagerPayment manager handle. Exposes balance subscription, top-ups and payment
PaymentRequestA payment the product asks the user to approve: an id it chooses, the amount and the payee.
PocketCardOne of the calling product’s Pocket cards.
PocketManagerPocket manager handle.
PreimageManagerPreimage manager handle for bulletin chain operations, backed by
ProductAccountIdIdentifies a product-specific account by combining a dotNS domain name with a
RendererManagerRenderer manager handle.
RenderRegistrationHandle for one claimed context.
ResultAsyncNeverthrow-style ResultAsync returned by product-sdk methods.
RingLocationLocates a ring for ring VRF operations using only identifiers that are
SignedStatementA statement with a required (not optional) proof.
StatementA statement with optional proof and metadata.
ThemeProviderHost theme provider handle. subscribeTheme(callback) receives a typed
TopUpRequestA top-up the product starts: an id it chooses, the amount and where the funds come from.

Type Aliases

NameSummary
AllocatableResourceA resource the host can pre-allocate on behalf of the product (RFC 0010).
AllocatableResourceA resource the host can pre-allocate on behalf of the product (RFC 0010).
AllocationOutcomeOutcome of allocating a single resource (RFC 0010).
AllocationOutcomeOutcome of allocating a single resource (RFC 0010).
CardCleanupWhat a card’s handler returns: what to run when the card leaves the screen.
CardDrawHandlerCalled when the host puts a card on screen, with the sink to draw into.
ChatBotRegistrationResultResult of registering a bot ("New" | "Exists"). Re-exported from @parity/truapi.
ChatCustomMessageRenderingRequestHandlerProduct callback that streams native renderer trees for one custom message.
ChatMessageContentContent of a chat message — one of several types.
ChatMessageContentContent of a chat message — one of several types.
ChatReceivedActionAction received via ChatManager.subscribeAction ({ roomId, peer, payload }). Re-exported from @parity/truapi.
ChatRoom—
ChatRoomRegistrationResultResult of registering a chat room: its status ("New" | "Exists") and the
ContextualAliasA contextual alias obtained from Ring VRF.
DerivationIndexAccount selector within a product subtree. Encodes as
DerivationIndexAccount selector within a product subtree. Encodes as
DevicePermissionKindDevice permission the dapp can ask the host to grant via
FeatureA feature the host can be probed for via featureSupported.
FinishedNftPurseStatusThe final status of an NFT move operation.
HexStringHex-encoded byte string, e.g. "0xdeadbeef".
HostAccountOne of the user’s existing wallet accounts, surfaced through the host and
HostChainIdentifierChain-role identifier. A closed protocol enum, not a free-form name. The
HostConnectionStatusConnection lifecycle of the host channel: "connecting" while the client waits
HostErrorPayloadThe error a host call puts on its Err channel — truapi’s canonical
HostNftPurseCreateChequeRequest—
HostNftPurseCreateItemsRequest—
HostNftPurseCreatePurseRequest—
HostNftPurseCreateReceiveKeyRequest—
HostNftPurseDepositRequest—
HostNftPurseListenOneTimePaymentItemStream item of listen_one_time_payment.
HostNftPurseListenOneTimePaymentItemStream item of listen_one_time_payment.
HostNftPurseListenOneTimePaymentRequest—
HostNftPurseListenPaymentInboxItemStream item of listen_payment_inbox.
HostNftPurseListenPaymentInboxItemStream item of listen_payment_inbox.
HostNftPurseListenPaymentInboxRequest—
HostNftPurseListPursesRequest—
HostNftPurseObserveOperationStatusRequest—
HostNftPurseQueryPurseRequest—
HostNftPurseRebalancePurseRequest—
HostNftPurseRefundRequest—
HostNftPurseRefundResponse—
HostNftPurseRevokeChequeRequest—
HostNftPurseTransferItemRequest—
HostPaymentBalanceSubscribeItem—
HostPaymentStatusSubscribeItemPayment lifecycle status pushed to subscribers.
HostPaymentStatusSubscribeItemPayment lifecycle status pushed to subscribers.
HostPaymentTopUpStatusSubscribeItemProgress of a top-up. Claimed { finalized: true }, ClaimedPartially and
HostPaymentTopUpStatusSubscribeItemProgress of a top-up. Claimed { finalized: true }, ClaimedPartially and
LocaleInfoHost locale value. A { languageTag } struct re-exported from
NftPurseCheque—
NftPurseChequeDestinationWhere a cheque’s items go.
NftPurseChequeDestinationWhere a cheque’s items go.
NftPurseChequeIdId of a cheque, and the idempotency key of its deposit.
NftPurseChequeIdId of a cheque, and the idempotency key of its deposit.
NftPurseChequeRecipientThe part of a destination the recipient needs to find its decryption key.
NftPurseChequeRecipientThe part of a destination the recipient needs to find its decryption key.
NftPurseClearedItem—
NftPurseClearingReference—
NftPurseIdId of an NFT purse. Ids are allocated in order from 0. The main purse,
NftPurseIdId of an NFT purse. Ids are allocated in order from 0. The main purse,
NftPurseIdempotencyKeyKey a product chooses for one chain operation. It is scoped to that
NftPurseIdempotencyKeyKey a product chooses for one chain operation. It is scoped to that
NftPurseInfoPage—
NftPurseItemKeyPublic key of one item in a purse. The host holds its secret.
NftPurseItemKeyPublic key of one item in a purse. The host holds its secret.
NftPurseOwnerWho owns an NFT purse.
NftPurseOwnerWho owns an NFT purse.
NftPursePaymentTransmissionChannelChannel a receiver listens on for a cheque.
NftPursePaymentTransmissionChannelChannel a receiver listens on for a cheque.
NftPursePurse—
NftPurseReceiveKeyOne-time key a receiver hands to the sender to start a payment.
NftPurseReceiveKeyOne-time key a receiver hands to the sender to start a payment.
NftPurseStatusProgress of an operation that moves items.
NftPurseStatusProgress of an operation that moves items.
NotificationIdHost-assigned id for a scheduled notification — pass to
PaymentTopUpSourceSource for a payment top-up operation.
PaymentTopUpSourceSource for a payment top-up operation.
PocketCard—
PocketCardActionA press or a value change inside one of the product’s card faces.
ProductAccountA product account — an app-scoped derived account managed by the host wallet.
ProductAccountId—
ProductAccountLookupHow callers address a product account: app identifier plus an optional index,
ProductIdA product identifier. Rust validates identifiers received by the host.
ProductIdA product identifier. Rust validates identifiers received by the host.
ProductProofContextThe product-scoped proof context ({ productId, suffix }), expanded by the
PushNotificationErrorPush notification error.
PushNotificationErrorPush notification error.
PushNotificationInputPush payload: text, an optional deeplink, and an optional scheduledAt
RegisteredRingVrfKeyRegistered key metadata returned by the host.
RemotePermissionOne remote-operation permission requested by the product (RFC 0002).
RemotePermissionOne remote-operation permission requested by the product (RFC 0002).
RemotePermissionItemLegacy alias of RemotePermission, kept for back-compat with code that
RenderCleanupWhat a render handler returns: what to run when the body leaves the screen.
RenderContextTagWhich kind of body the host is asking for.
RenderFailureThe reason carried on the interrupt channel when a body cannot be drawn.
RenderHandlerDraws one kind of body.
RingLocation—
RingVrfKeyDisclosureHow much of a registry entry the caller asks for.
RingVrfKeyDisclosureHow much of a registry entry the caller asks for.
RingVrfKeyHandleOpaque public name of a registered ring-VRF key.
RingVRFProofA Ring VRF proof plus the values needed to verify it downstream (e.g.
RingVrfPublicKeyRing-VRF member public key, decoded from the wire’s hex string.
SignedStatement—
Statement—
StatementProofCryptographic proof for a statement.
StatementProofCryptographic proof for a statement.
StatementsPageA page of signed statements delivered by HostStatementStore.subscribe.
StatementTopicFilterTopic-based subscription filter. The host delivers statements that match
ThemeModeHost theme value. A { name, variant } struct re-exported from
ThemeNameIdentifies a named theme.
ThemeNameIdentifies a named theme.
ThemeVariantLight or dark variant.
ThemeVariantLight or dark variant.
Topic—
TruApiThe TruApi client — namespaced access to every host protocol domain
VrfSignatureAn sr25519 VRF signature: the pre-output and its DLEQ proof.
VrfTranscriptItemOne append_message(label, value) call replayed against a VRF transcript.
WithDecodeErrorA call’s declared Err channel, plus HostResponseDecodeError: any
X25519PublicKeyX25519 public key for key agreement (RFC 0022).
X25519PublicKeyX25519 public key for key agreement (RFC 0022).

Variables

NameSummary
BULLETIN_RPCSBulletin Chain RPC endpoints per network environment. paseo (Paseo Next v2),
DEFAULT_BULLETIN_ENDPOINTDefault Bulletin Chain endpoint — the first entry under BULLETIN_RPCS.paseo.
MAIN_NFT_PURSE_IDID of the main purse. Its owner is Root, which means that no product owns
NFT_PURSE_MAX_ITEMS_PER_CALLThe max number of items that one createItems call can create.
NFT_PURSE_MAX_NAME_BYTESThe max length of a purse name, in UTF-8 bytes.
NFT_PURSE_MAX_PAGE_SIZEThe max number of items in one queryPurse page.

Re-exports

Convenience re-exports from leaf packages. Click through for the canonical documentation.

NameKindSource package
err()function@parity/result
isSdkError()function@parity/product-sdk-errors
ok()function@parity/result
Resulttype@parity/result
SdkErrorinterface@parity/product-sdk-errors

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): ChainNotSupportedError

Properties

genesisHash
propertyreadonlystring

Genesis 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): HostCallFailedError

Properties

payload
propertyreadonlyHostErrorPayload

class HostError

Base class for all host errors. Use instanceof HostError (or isHostError) to catch any host-related failure. Implements the cross-package SdkError marker so isSdkError(e) also recognizes it.

Extends: Error

Implements: SdkError

Constructors

constructor
new HostError(message: string, options?: ErrorOptions): HostError

Properties

isSdkError
propertyreadonlytrue

Discriminant present on all SDK errors.

source
propertyreadonly"host"

The package that raised the error, e.g. "host", "signer", "contracts".

class HostResponseDecodeError

A host call could not be processed to completion: the ResultAsync the truapi client returns rejected instead of resolving to an ok/err. The usual cause is a response the client’s SCALE codec can’t decode (a RangeError: Offset is outside the bounds of the DataView) because the host and the @parity/truapi version the product is built against disagree on the wire shape of that call — a protocol-version skew. A host channel that closed mid-call looks identical from here, so this does not assert the skew; the real error is preserved on cause. A call the host never answers is the HostTimeoutError subclass, whose message says so.

The truapi client catches the decode throw in its message handler and turns it into a promise rejection, then wraps the call with ResultAsync.fromSafePromise, which installs no rejection handler — so the rejection escapes the Result channel rather than landing on its err side. Without this boundary that surfaces as a raw RangeError with a stack naming neither the call nor the cause. This names the call, so a bug report has somewhere to start.

Extends: HostError

Constructors

constructor
new HostResponseDecodeError(call: string, cause: unknown): HostResponseDecodeError

Properties

call
propertyreadonlystring

The host-API call whose response failed to decode, e.g. "createRingVRFProof".

class HostTimeoutError

A host call got no answer before the truapi client’s deadline. The client asks the host to cancel the call, but the host may already have acted on it, for example a person approving on their phone, so check the outcome before retrying. The client’s RequestTimeoutError is preserved on cause.

It is a HostResponseDecodeError, so code that handles a call the client could not complete handles a timeout too, but its message does not blame a protocol-version skew.

Extends: HostResponseDecodeError

Constructors

constructor
new HostTimeoutError(call: string, cause: RequestTimeout): HostTimeoutError

Properties

timeoutMs
propertyreadonlynumber

How long the client waited, in milliseconds.

class 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"): HostUnavailableError

Functions

asProductId()

Designate a product identifier without changing or validating its value.

asProductId(value: string): ProductId

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: The 0x-prefixed genesis hash of the target chain.
  • transaction: The 0x-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.

Deprecated. Use getHostLocalStorage; this is an identical alias kept for back-compat and will be removed in a future major.

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.

Deprecated. Use getPreimageManager; this is an identical alias kept for back-compat and will be removed in a future major.

createHostPreimageManager(): Promise<PreimageManager | null>

Returns

A PreimageManager instance, or null if unavailable.

createHostTxCreator()

Build a creator that signs through sendToHost.

createHostTxCreator(publicKey: Uint8Array, sendToHost: (request: HostTxRequest) => Promise<`0x${string}`>, signBytes: (data: Uint8Array) => Promise<Uint8Array<ArrayBufferLike>>, preferredTxExtVersion: number = 0): CommonSignerTxCreator

Parameters

  • publicKey: the account the host signs with, used for the nonce and the mocked signature.
  • sendToHost: one host round trip, returning the signed extrinsic as hex.
  • signBytes: raw byte signing for the same account.
  • preferredTxExtVersion: the version to sign on when the payload names none and that pipeline carries every supplied extension.

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; }

deriveRefundIdempotencyKey()

Returns the idempotency key to pass to observeOperationStatus for the refund of a deposited cheque.

deriveRefundIdempotencyKey(chequeId: `0x${string}`): `0x${string}`

deriveRevokeIdempotencyKey()

Returns the idempotency key to pass to observeOperationStatus for the revoke of a cheque.

deriveRevokeIdempotencyKey(chequeId: `0x${string}`): `0x${string}`

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) { ... }

findRingVrfKeyHandle()

Select a registered key by its declared ring and return its opaque handle.

Consumers must not hard-code another product’s derivation index. Registry order breaks ties when an owner declares multiple keys for the same ring.

findRingVrfKeyHandle(keys: RegisteredRingVrfKey[], ring: RingLocation): RingVrfKeyHandle | undefined

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): string

fromHex()

Convert a hex string (with or without 0x) to bytes.

fromHex(hex: string): Uint8Array

getAccountsProvider()

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: The 0x-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) => { ... }); }

getHostChainInfo()

Resolve chain roles against the current host.

Returns null when discovery is unavailable: outside a container, on a legacy host, or when the host serves none of the requested identifiers. Callers treat null as “fall back to configured constants”.

One concurrent getChainInfo call is made per identifier. Identifiers the host answers NotSupported for are absent from chains. Stable answers are cached per client and identifier set. Unexpected wire failures and probe timeouts are logged, return null and are not cached, so a later call re-probes.

getHostChainInfo(identifiers: readonly ChainIdentifier[]): Promise<HostChainDiscovery | null>

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.

getLocaleProvider()

Get the host locale provider, backed by truApi.locale.*. Returns null when running outside a host container.

The tag is whatever the host reports; a product that ships no catalog entry for it chooses its own fallback.

getLocaleProvider(): Promise<LocaleProvider | null>

Returns

The locale provider, or null if unavailable.

Examples

import { getLocaleProvider } from "@parity/product-sdk-host"; const provider = await getLocaleProvider(); if (provider) { const sub = provider.subscribeLocale((locale) => { i18n.activate(SUPPORTED.has(locale.languageTag) ? locale.languageTag : "en"); }); // sub.unsubscribe() to stop listening }

getNftPurseManager()

Returns the NFT purse manager, or null outside a host. On a host that has no NFT purses every call fails with Unsupported.

getNftPurseManager(): Promise<NftPurseManager | null>

Examples

import { asProductId, getNftPurseManager, isNftPurseOperationFinished, NFT_PURSE_MAX_PAGE_SIZE, toHex, } from "@parity/product-sdk-host"; const purses = await getNftPurseManager(); if (purses) { const owner = { tag: "Product", value: asProductId("collectibles.dot") } as const; const purseNamed = async (name: string) => { const existing = (await purses.listPurses({ owner })).find((purse) => purse.name === name); return existing?.id ?? (await purses.createPurse({ name })); }; const collectibles = await purseNamed("collectibles"); const archive = await purseNamed("archive"); const [mintTarget] = await purses.createItems({ purse: collectibles, count: 1 }); // ...mint an NFT to `mintTarget` on chain... const { items } = await purses.queryPurse({ purse: collectibles, page: 0, pageSize: NFT_PURSE_MAX_PAGE_SIZE, }); const idempotencyKey = toHex(crypto.getRandomValues(new Uint8Array(32))); await purses.rebalancePurse({ from: collectibles, to: archive, keys: items, idempotencyKey }); purses.observeOperationStatus({ idempotencyKey }, (status) => { if (isNftPurseOperationFinished(status)) console.log(status.tag); }); }

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, newPaymentId } from "@parity/product-sdk-host"; const payments = await getPaymentManager(); if (payments) { const sub = payments.subscribeBalance((b) => { ... }); const topUp = newPaymentId(); await payments.topUp({ id: topUp, amount: 1_000_000n, source: { tag: "ProductAccount", value: { derivationIndex: { tag: "Index", value: 0 } } }, }); payments.subscribeTopUpStatus(topUp, (status) => { ... }); const payment = newPaymentId(); await payments.requestPayment({ id: payment, amount: 500n, destination: "0x…" }); payments.subscribePaymentStatus(payment, (status) => { ... }); sub.unsubscribe(); }

getPocketManager()

Get the host Pocket manager. Returns null when running outside a host container.

getPocketManager(): Promise<PocketManager | null>

Examples

import { getPocketManager } from "@parity/product-sdk-host"; const pocket = await getPocketManager(); pocket?.subscribeCards((cards) => console.log(cards.map((card) => card.cardId)));

getPreimageManager()

Get the preimage manager for bulletin chain operations.

getPreimageManager(): Promise<PreimageManager | null>

Returns

The preimage manager, or null if unavailable (outside a container).

getRendererManager()

Get the renderer manager, for drawing a body the SDK has no wrapper for. Returns null when running outside a host container.

getRendererManager(): Promise<RendererManager | null>

Examples

import { getRendererManager } from "@parity/product-sdk-host"; const renderer = await getRendererManager(); renderer?.draw("ChatMessage", (request, send) => { send(body()); });

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.

hostErrorName()

Returns the name of the host’s error, for example OperationExists or Unsupported. Pass it the error that a host call threw, or the reason that onInterrupt received. Returns undefined when the error is not from the host.

hostErrorName(error: unknown): string | undefined

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’s 0x-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 HostError

isInsideContainer()

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()

Host-container detection. true when a test client is injected, otherwise the sandbox heuristic (iframe / webview marker / injected message port).

isInsideContainerSync(): boolean

isNftPurseOperationFinished()

Returns true when an operation is finished. Cleared means every NFT moved in a finalized block. Incomplete means some moves failed.

isNftPurseOperationFinished(status: NftPurseStatus): status is FinishedNftPurseStatus

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);

newPaymentId()

A fresh random 32-byte id for a top-up or payment request.

Prefer an id derived from the product’s own state when it has one (an order id, a session and step): a restart then finds the same id again, and the host answers AlreadyExists instead of moving funds twice. A random id is only safe when the product stores it before it starts the top-up or payment.

newPaymentId(): `0x${string}`

registerRenderContext()

Claim one render context on this client.

Claiming a second context leaves the first alone. Claiming one that is already claimed replaces its handler, which is what the raw slot would do.

registerRenderContext(client: TrUApiClient, tag: "ChatMessage" | "InputWidget" | "PocketCard" | "PocketCardBack" | "ChatRoomFooter", handler: RenderHandler): RenderRegistration

renderFailure()

Build the reason, so a refusal reaches the host instead of dying here.

renderFailure(reason: string): RenderFailure

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: The 0x-prefixed genesis hash of the target chain.
  • operationId: The operation id returned by broadcastTransaction.

Returns

ok on success, or err(HostUnavailableError | HostCallFailedError).

Examples

await stopTransaction(genesisHash, operationId);

subscribeConnectionStatus()

Subscribe to host-channel connection status. The callback fires synchronously with the current status and again on every change; the returned function unsubscribes. Repeats of the status you already have are suppressed.

This is the transport channel. For the host’s account-level connection — what drives @parity/product-sdk-signer’s ConnectionStatus — use AccountsProvider.subscribeAccountConnectionStatus instead.

Subscribing is not passive: outside an established channel the first subscribe builds the client and provider, so this can be what constructs the transport.

Honours the setTruApiClient seam — an injected client is connected by definition, and injecting or clearing one notifies live subscribers.

subscribeConnectionStatus(callback: (status: ConnectionStatus) => void): () => void

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 PAPI TxCreator factories.

Lookup methods return a neverthrow ResultAsync (use .match(ok, err)); the signer factories return a synchronous PAPI TxCreator. The err channel carries truapi’s canonical CallErrorValue envelope around the per-call versioned domain error, exactly as the generated client returns it, plus a HostResponseDecodeError when the host’s reply cannot be decoded at all (a host/client protocol-version skew) or, as its HostTimeoutError subclass, when the host does not answer in time; see WithDecodeError.

Methods

createRingVRFProof

Generate a Ring VRF proof with an explicitly registered key, binding message to the product-scoped context.

createRingVRFProof(keyHandle: RingVrfKeyHandle, context: ProductProofContext, location: RingLocation, message: Uint8Array): ResultAsync<RingVRFProof, WithDecodeError<CallErrorValue<VersionedHostAccountCreateProofError>>>
getLegacyAccounts
getLegacyAccounts(): ResultAsync<HostAccount[], WithDecodeError<CallErrorValue<VersionedHostGetLegacyAccountsError>>>
getLegacyAccountSigner

Build a PAPI 3 TxCreator for one of the existing wallet accounts of the user. name is accepted for callsite ergonomics but unused — the signer is derived from publicKey alone.

getLegacyAccountSigner(account: { name?: string; publicKey: Uint8Array }, options?: HostSignerOptions): CommonSignerTxCreator
getProductAccount
getProductAccount(dotNsIdentifier: string, derivationIndex?: number): ResultAsync<ProductAccount, WithDecodeError<CallErrorValue<VersionedHostAccountGetError>>>
getProductAccountAlias

Derive a contextual alias with an explicitly registered ring-VRF key.

getProductAccountAlias(keyHandle: RingVrfKeyHandle, context: ProductProofContext, location: RingLocation): ResultAsync<ContextualAlias, WithDecodeError<CallErrorValue<VersionedHostAccountGetAliasError>>>
getProductAccountSigner

Build a PAPI 3 TxCreator for a product account. Signing routes through the host createTransaction path, which forwards the opaque extension bytes, so unknown extensions survive end-to-end.

getProductAccountSigner(account: ProductAccount, options?: HostSignerOptions): CommonSignerTxCreator
getUserId
getUserId(): ResultAsync<{ primaryUsername: string }, WithDecodeError<CallErrorValue<VersionedHostGetUserIdError>>>
listRingVrfKeys

List an owner’s registered ring-VRF keys.

listRingVrfKeys(owner: string, disclosure?: RingVrfKeyDisclosure): ResultAsync<RegisteredRingVrfKey[], WithDecodeError<CallErrorValue<VersionedHostAccountListRingVrfKeysError>>>
registerRingVrfKey

Register a ring-VRF key owned by the calling product.

index is the plain derivation index within the product’s ring-VRF domain; the adapter wraps it into the wire’s tagged selector.

Registration returns the key’s public key. Call listRingVrfKeys afterward to obtain the opaque handle required by alias and proof calls.

registerRingVrfKey(index: number, ring: RingLocation): ResultAsync<RingVrfPublicKey, WithDecodeError<CallErrorValue<VersionedHostAccountRegisterRingVrfKeyError>>>
requestLogin
requestLogin(reason?: string): ResultAsync<HostRequestLoginResponse, WithDecodeError<CallErrorValue<VersionedHostRequestLoginError>>>
ringVrfSign

Sign message directly with an explicitly registered ring-VRF key.

Unlike createRingVRFProof this proves nothing about ring membership; it is the plain signature under the member key, for protocols that carry their own proof.

ringVrfSign(keyHandle: RingVrfKeyHandle, message: Uint8Array): ResultAsync<Uint8Array<ArrayBufferLike>, WithDecodeError<CallErrorValue<VersionedHostAccountRingVrfSignError>>>
signRawUnwatermarkedDeprecated
signRawUnwatermarkedDeprecated(account: ProductAccount, data: Uint8Array): Promise<Uint8Array<ArrayBufferLike>>
signRawUnwatermarkedDeprecatedWithLegacyAccount
signRawUnwatermarkedDeprecatedWithLegacyAccount(account: { publicKey: Uint8Array }, data: Uint8Array): Promise<Uint8Array<ArrayBufferLike>>
signVrf

Produce an sr25519 VRF signature from a product account (RFC-0023).

The host builds a Merlin transcript from transcriptLabel and items, then signs it with the account’s key. Unlike createRingVRFProof, this names the signing account instead of proving ring membership.

The caller owns four things the types cannot enforce:

  • Domain separation. A label borrowed from another protocol makes the output replayable across both.
  • Freshness. The VRF is deterministic, so per-round values belong in items.
  • Size. Hosts cap the transcript at 32 items and 8 KiB total.
  • Authorization. An AutoSigning allowance makes these calls silent. It is not VRF-scoped, so it covers other signing by that account too.

Hosts predating the call reject it through the error channel.

signVrf(account: ProductAccountLookup, transcriptLabel: Uint8Array, items: VrfTranscriptItem[]): ResultAsync<VrfSignature, WithDecodeError<CallErrorValue<VersionedHostAccountSignVrfError>>>
subscribeAccountConnectionStatus
subscribeAccountConnectionStatus(callback: (status: HostAccountConnectionStatusSubscribeItem) => void): HostSubscription

interface CardDrawRegistration

Handle for one card’s registration.

There is no onInterrupt here, unlike a subscription: renderer.onRender is a registration rather than a stream, and the host has no channel to interrupt it through.

Methods

unsubscribe
unsubscribe(): void

interface 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
propertyoptionalnumber

Address prefix used for SS58 encoding (e.g. 0 for Polkadot).

tokenDecimals
propertyoptionalnumber | number[]

Decimal places of the chain’s native token(s).

tokenSymbol
propertyoptionalstring | string[]

Ticker symbol(s) of the chain’s native token(s).

interface ChainSpec

Combined chain-spec view returned by getChainSpec.

Properties

genesisHash
property`0x${string}`

The chain’s 0x-prefixed genesis hash, as reported by the host.

name
propertystring

Human-readable chain name (e.g. "Polkadot").

properties
propertyChainProperties | null

Parsed chain properties, or null if the host’s JSON payload couldn’t be parsed. Inspect propertiesRaw for the original string.

propertiesRaw
propertystring

The untouched JSON string the host returned for properties.

interface ChatCustomMessageRenderingRegistration

Registration returned by the custom-message renderer channel.

Methods

unsubscribe
unsubscribe(): void

interface ChatCustomMessageRenderingRequest

Request delivered when the host needs a native tree for a stored custom message.

Properties

messageId
propertystring
messageType
propertystring
payload
propertyUint8Array

Methods

subscribeActions
subscribeActions(callback: (actionId: string, payload: Uint8Array<ArrayBufferLike> | undefined) => void): VoidFunction

interface ChatManager

Chat manager handle. Exposes room/bot registration, message sending, and subscription to the room list and incoming actions.

Methods

onCustomMessageRenderingRequest
onCustomMessageRenderingRequest(handler: ChatCustomMessageRenderingRequestHandler): ChatCustomMessageRenderingRegistration
registerBot
registerBot(request: HostChatRegisterBotRequest): Promise<ChatBotRegistrationStatus>
registerRoom
registerRoom(request: HostChatCreateRoomRequest): Promise<HostChatCreateRoomResponse>
sendMessage
sendMessage(roomId: string, payload: ChatMessageContent, options?: ChatSendMessageOptions): Promise<{ messageId: string }>
subscribeAction
subscribeAction(callback: (action: HostChatActionSubscribeItem) => void): HostSubscription
subscribeChatList
subscribeChatList(callback: (rooms: ChatRoom[]) => void): HostSubscription

interface ChatRoom

A chat room the product participates in.

Properties

participatingAs
propertyChatRoomParticipation

RoomHost or Bot.

roomId
propertystring

Room identifier.

interface ChatSendMessageOptions

Options for ChatManager.sendMessage.

Properties

alt
propertyoptionalstring

One line describing the message, which a host shows where it lists the message rather than draws it, such as a chat list preview of a custom card.

interface HostChainDiscovery

The host’s configured environment plus per-identifier resolved genesis hashes.

Properties

chains
propertyPartial<Record<HostChainIdentifier, HexString>>

Present for every requested identifier the host serves.

network
propertystring

Ecosystem the host is configured for, e.g. "polkadot", "paseo".

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 HostNftPurseCreateChequeRequest

Request to hand items off in a cheque.

Properties

from
propertynumber

Source purse.

items
property`0x${string}`[]

Items to hand off.

to
propertyNftPurseChequeDestination

Recipient.

interface HostNftPurseCreateItemsRequest

Request to create new item keys in a purse.

Properties

count
propertynumber

Number of keys, in 1..=1000.

purse
propertynumber

Purse that receives the keys.

interface HostNftPurseCreatePurseRequest

Request to create a purse owned by the caller.

Properties

name
propertystring

Purse name, at most [NFT_PURSE_MAX_NAME_BYTES] bytes.

interface HostNftPurseCreateReceiveKeyRequest

Request for a one-time receive key.

Properties

into
propertynumber

Purse the received items go into.

interface HostNftPurseDepositRequest

Request to deposit a received cheque.

Properties

cheque
propertyNftPurseCheque

The received cheque. Its id is the idempotency key.

to
propertynumber

Purse the items go into.

interface HostNftPurseListenOneTimePaymentRequest

Request to wait for a cheque sent to a receive key.

Properties

key
property`0x${string}`

Receive key from create_receive_key.

interface HostNftPurseListenPaymentInboxRequest

Request to listen to one of the caller’s payment inboxes.

Properties

inboxDomain
property`0x${string}`

Which of the caller’s inboxes to listen to. The product picks it and publishes it with its payment instructions.

interface HostNftPurseListPursesRequest

Request to list an owner’s purses.

Properties

owner
propertyNftPurseOwner

Whose purses.

interface HostNftPurseObserveOperationStatusRequest

Request for the status of an operation the calling product registered.

Properties

idempotencyKey
property`0x${string}`

The key the operation was registered under: the cheque id of a deposit, or blake2_256("nft-purse/revoke" ‖ chequeId) and blake2_256("nft-purse/refund" ‖ chequeId) for a revoke and a refund.

interface HostNftPurseQueryPurseRequest

Request for one page of a purse’s spendable items.

Properties

page
propertynumber

Zero-based page index.

pageSize
propertynumber

Items per page, in 1..=100.

purse
propertynumber

Purse to read.

interface HostNftPurseRebalancePurseRequest

Request to move items between purses.

Properties

from
propertynumber

Source purse.

idempotencyKey
property`0x${string}`

Names the operation for observe_operation_status.

keys
property`0x${string}`[]

Items to move.

to
propertynumber

Destination purse.

interface HostNftPurseRefundRequest

Request to return a deposited cheque’s items to their original keys.

Properties

chequeId
property`0x${string}`

The deposited cheque.

interface HostNftPurseRefundResponse

The refund’s moves, by the depositing purse’s item keys.

Properties

started
property`0x${string}`[]

Items whose move back to their cheque key started.

unavailable
property`0x${string}`[]

Items the deposit brought in that were spent since, and stay.

interface HostNftPurseRevokeChequeRequest

Request to release the items of an undelivered cheque.

Properties

chequeId
property`0x${string}`

Cheque to revoke.

interface HostNftPurseTransferItemRequest

Request to move one item to a key outside the purses.

Properties

destination
property`0x${string}`

Key that receives it.

idempotencyKey
property`0x${string}`

Names the operation for observe_operation_status.

item
property`0x${string}`

Item to move.

interface HostPaymentBalanceSubscribeItem

Current payment balance state pushed to subscribers.

See RFC 0006 .

Properties

available
propertybigint

Balance that can be spent right now.

interface HostSignerOptions

Transaction settings for host-backed signers.

Properties

txExtVersion
propertyoptionalnumber

Pipeline version to prefer when the transaction names none. Defaults to 0.

When that pipeline does not declare every extension the caller supplied, for example in customSignedExtensions, the signer uses the lowest version that does, and refuses a transaction no pipeline can carry. A wrapper that writes its own extensions, such as withAsPerson, sets the version on the transaction itself, and that always wins.

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): HostSubscription

interface 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): () => void
unsubscribe
unsubscribe(): void

interface HostTxExtension

One extension as the host signs it.

Properties

additionalSigned
property`0x${string}`
extra
property`0x${string}`
id
propertystring

interface HostTxRequest

What the host needs to build and sign one transaction.

Properties

callData
property`0x${string}`
extensions
propertyHostTxExtension[]
genesisHash
property`0x${string}`
txExtVersion
propertynumber

interface LocaleProvider

Host locale provider handle. subscribeLocale(callback) receives a typed LocaleInfo on every change and returns a HostSubscription.

Methods

subscribeLocale
subscribeLocale(callback: (locale: HostLocaleSubscribeItem) => void): HostSubscription

interface NftPurseCheque

Items handed off to a recipient.

Properties

encryptedSecrets
property`0x${string}`

Item secrets, encrypted to the recipient.

id
property`0x${string}`

Cheque id.

items
property`0x${string}`[]

Keys of the handed-off items.

recipient
propertyNftPurseChequeRecipient

Who can decrypt it.

version
propertynumber

Cheque format version, 0.

interface NftPurseClearedItem

One item an operation moved.

Properties

consumed
property`0x${string}`

Source key, from the origin purse or from the cheque.

finalized
propertyboolean

Whether the moving transaction is finalized.

minted
property`0x${string}`

Destination key, in the destination purse.

interface NftPurseClearingReference

Product-visible clearing reference.

Properties

leaves
property[`0x${string}`, `0x${string}`][]

Source item key and the hash of the transaction that moved it, sorted by item key.

root
property`0x${string}`

Binary Merkle root of the SCALE-encoded leaves, as binary_merkle_tree::merkle_root computes it with Blake2-256. A verifier must check the leaf count.

interface NftPurseInfoPage

One page of the spendable items of a purse.

Properties

hasNext
propertyboolean

Whether a later page holds more items.

items
property`0x${string}`[]

Keys of items present on chain and not in use.

interface NftPurseManager

The NFT purse calls of the host. A call that fails throws an Error with the host’s error as cause, and hostErrorName returns the name of that error.

Methods

createCheque

Creates a cheque for items and returns it. The product sends the cheque to the recipient. The purse cannot use these items after this call. A second cheque with the same id fails with OperationExists.

createCheque(request: HostNftPurseCreateChequeRequest): Promise<NftPurseCheque>
createItems

Creates new items in a purse and returns their public keys. One call creates up to NFT_PURSE_MAX_ITEMS_PER_CALL items.

createItems(request: HostNftPurseCreateItemsRequest): Promise<`0x${string}`[]>
createPurse

Creates a purse for this product and returns its id. The host allows duplicate purses. Call listPurses first to make sure that your purse does not already exist.

createPurse(request: HostNftPurseCreatePurseRequest): Promise<number>
createReceiveKey

Creates a one-time receive public key for a purse. The product gives it to the sender.

createReceiveKey(request: HostNftPurseCreateReceiveKeyRequest): Promise<`0x${string}`>
deposit

Moves the NFTs of a received cheque to new items of a purse. The cheque id is the idempotency key.

deposit(request: HostNftPurseDepositRequest): Promise<void>
listenOneTimePayment

Subscribes to the cheque sent to a receive public key of this product. The callback first gets the channel, which has the statement store topic for that receive public key. Then it gets the cheque, and the subscription ends.

listenOneTimePayment(request: HostNftPurseListenOneTimePaymentRequest, onUpdate: (update: HostNftPurseListenOneTimePaymentItem) => void): HostSubscription
listenPaymentInbox

Subscribes to Static cheques sent to one inbox of this product. Every time the subscription opens, the callback first gets the channel, which has the statement store topic of the inbox. Then it gets all cheques that the statement store still has, including deposited ones, so ignore the cheque ids that are already deposited. After that the callback gets new cheques.

listenPaymentInbox(request: HostNftPurseListenPaymentInboxRequest, onUpdate: (update: HostNftPurseListenPaymentInboxItem) => void): HostSubscription
listPurses

Returns the purses of an owner. The NftPurseRead permission is needed for the purses of another product or of Root.

listPurses(request: HostNftPurseListPursesRequest): Promise<NftPursePurse[]>
observeOperationStatus

Calls onStatus with the status of an operation until the operation is finished. Use the idempotency key of a rebalance or a transfer, or the cheque id of a deposit. For a revoke use deriveRevokeIdempotencyKey, and for a refund deriveRefundIdempotencyKey.

observeOperationStatus(request: HostNftPurseObserveOperationStatusRequest, onStatus: (status: NftPurseStatus) => void): HostSubscription
queryPurse

Returns one page of the items that hold an NFT on chain and are not in use. The first page is 0, and a page has up to NFT_PURSE_MAX_PAGE_SIZE items.

queryPurse(request: HostNftPurseQueryPurseRequest): Promise<NftPurseInfoPage>
rebalancePurse

Moves NFTs from items of one purse to new items of another purse. A second call with the same idempotency key fails with OperationExists.

rebalancePurse(request: HostNftPurseRebalancePurseRequest): Promise<void>
refund

Moves the NFTs of a deposited cheque back to the public keys in the cheque. Returns the items that the host started to move back and the items that were spent after the deposit. To follow the moves, pass deriveRefundIdempotencyKey of the cheque id to observeOperationStatus.

refund(request: HostNftPurseRefundRequest): Promise<HostNftPurseRefundResponse>
revokeCheque

Cancels a cheque that this product created. The host moves the NFTs to new items of the purse they came from. After that the private keys in the cheque cannot move the NFTs. Fails with ItemsInUse when the NFTs are already being moved, for example by a deposit of the cheque on this device. Calling it again moves only the NFTs whose move failed. To follow the moves, pass deriveRevokeIdempotencyKey of the cheque id to observeOperationStatus.

revokeCheque(request: HostNftPurseRevokeChequeRequest): Promise<void>
staticReceiveKey

Returns the X25519 public key that senders encrypt Static cheques to. Every product gets the same one. The user has to agree to disclose their identity before the host returns it, and the call fails with PermissionDenied when the user does not agree.

staticReceiveKey(): Promise<`0x${string}`>
transferItem

Moves the NFT of one item to a public key outside the purses.

transferItem(request: HostNftPurseTransferItemRequest): Promise<void>

interface NftPursePurse

A purse as list_purses reports it.

Properties

id
propertynumber

Purse id.

name
propertystring

Name given at creation, or chosen by the host after a recovery that lost it.

interface 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-ups and payment requests by id, and a status subscription for each.

The balance / status / top-up-source shapes are @parity/truapi’s HostPaymentBalanceSubscribeItem, HostPaymentStatusSubscribeItem, HostPaymentTopUpStatusSubscribeItem and PaymentTopUpSource — used directly rather than re-aliased.

Methods

requestPayment

Ask the user to approve a payment. Resolves once the user approved it; follow it with subscribePaymentStatus.

requestPayment(request: PaymentRequest): Promise<void>
subscribeBalance

Follow the spendable balance of purse (the main purse when omitted).

Needs the BalanceAccess permission. Without it, or once it is revoked, the subscription ends and its onInterrupt callback receives the host’s PermissionDenied error.

subscribeBalance(callback: (balance: HostPaymentBalanceSubscribeItem) => void, purse?: number): HostSubscription
subscribePaymentStatus

Follow a payment by its id. Completed, ClaimedPartially and Failed are final; the host keeps answering them after the payment ends.

subscribePaymentStatus(id: `0x${string}`, callback: (status: HostPaymentStatusSubscribeItem) => void): HostSubscription
subscribeTopUpStatus

Follow a top-up by its id. Claimed { finalized: true }, ClaimedPartially and NotClaimed are final; the host keeps answering them after the top-up ends.

subscribeTopUpStatus(id: `0x${string}`, callback: (status: HostPaymentTopUpStatusSubscribeItem) => void): HostSubscription
topUp

Start a top-up. Resolves once the host has taken it; follow it with subscribeTopUpStatus.

topUp(request: TopUpRequest): Promise<void>

interface PaymentRequest

A payment the product asks the user to approve: an id it chooses, the amount and the payee.

Properties

amount
propertybigint

Amount in balance units. Zero is refused as InvalidAmount.

destination
property`0x${string}`

32-byte account the payment goes to.

from
propertyoptionalnumber

Purse to pay from; omitted pays from the main purse.

id
property`0x${string}`

32-byte id. Reusing one is answered AlreadyExists.

interface PocketCard

One of the calling product’s Pocket cards.

Properties

cardId
propertystring

Card label declared by the product, unique within the product.

privileged
propertyboolean

Placed by the host itself; removable by neither the user nor the product.

interface PocketManager

Pocket manager handle.

Methods

drawCard

Draw cardId whenever the host puts it on screen.

Drawing a card that is already being drawn replaces the handler, and the older handle’s unsubscribe then does nothing, so the live handler cannot be torn down by a stale one.

drawCard(cardId: string, draw: CardDrawHandler): CardDrawRegistration
removeCard

Give a card up. Resolves when it is gone, and rejects when the host refuses, which it does for a card it placed itself. Removing a card that was never there succeeds.

The card’s draw handler stays registered, so the product draws the card again if the host ever puts it back.

removeCard(cardId: string): Promise<void>
subscribeCardAction

Every action inside cardId’s face, and nothing else.

subscribeCardAction(cardId: string, callback: (action: HostRendererActionSubscribeItem) => void): HostSubscription
subscribeCards

The product’s cards, republished whenever the collection changes.

subscribeCards(callback: (cards: PocketCard[]) => void): HostSubscription

interface PreimageManager

Preimage manager handle for bulletin chain operations, backed by truApi.preimage.*. lookup opens a HostSubscription (unsubscribe

  • onInterrupt) that delivers the preimage bytes — or null until the host finds them; submit uploads a preimage and resolves to its 0x-prefixed hex key.

Methods

lookup
lookup(key: `0x${string}`, callback: (preimage: Uint8Array<ArrayBufferLike> | null) => void): HostSubscription
submit
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
propertyDerivationIndex

Account selector within the product subtree.

dotNsIdentifier
propertyProductId

A dotNS domain name identifier (e.g., "my-product.dot").

interface RendererManager

Renderer manager handle.

Methods

draw

Draw one kind of body. Returns a handle that gives the context back.

Reach for a surface’s own wrapper where there is one. getPocketManager() claims PocketCard for you and routes it per card.

draw(tag: "ChatMessage" | "InputWidget" | "PocketCard" | "PocketCardBack" | "ChatRoomFooter", handler: RenderHandler): RenderRegistration

interface RenderRegistration

Handle for one claimed context.

Methods

unsubscribe
unsubscribe(): void

interface ResultAsync

Neverthrow-style ResultAsync returned by product-sdk methods.

Use .match(onOk, onErr) to handle success/error cases.

Properties

match
property(ok: (t: T) => A, err: (e: E) => B) => Promise<A | B>

interface RingLocation

Locates a ring for ring VRF operations using only identifiers that are stable across membership changes.

Properties

chainId
property`0x${string}`

Genesis hash of the chain hosting the ring.

junctions
propertyRingLocationJunction[]

Path addressing the ring within the chain.

interface SignedStatement

A statement with a required (not optional) proof.

Properties

channel
propertyoptional`0x${string}`

Optional channel.

data
propertyoptional`0x${string}`

Optional data payload.

decryptionKey
propertyoptional`0x${string}`

Optional decryption key.

expiry
propertyoptionalbigint

Optional Unix timestamp expiry.

proof
propertyStatementProof

Required cryptographic proof.

topics
property`0x${string}`[]

[u8; 32] tags.

interface Statement

A statement with optional proof and metadata.

Properties

channel
propertyoptional`0x${string}`

Optional channel.

data
propertyoptional`0x${string}`

Optional data payload.

decryptionKey
propertyoptional`0x${string}`

Optional decryption key.

expiry
propertyoptionalbigint

Optional Unix timestamp expiry.

proof
propertyoptionalStatementProof

Optional cryptographic proof.

topics
property`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): HostSubscription

interface TopUpRequest

A top-up the product starts: an id it chooses, the amount and where the funds come from.

Properties

amount
propertybigint

Amount in balance units. Zero is refused as InvalidAmount.

id
property`0x${string}`

32-byte id. Reusing one is answered AlreadyExists.

into
propertyoptionalnumber

Purse to credit; omitted credits the main purse.

source
propertyPaymentTopUpSource

Where the funds come from.

Type 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: DerivationIndex } | { 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 CardCleanup

What a card’s handler returns: what to run when the card leaves the screen.

undefined in place of void would reject the ordinary (send) => send(face), whose inferred return is void. The protocol’s own HostInitiatedSubscriptionHandler is (() => void) | void for the same reason.

type CardCleanup = () => void | void

type CardDrawHandler

Called when the host puts a card on screen, with the sink to draw into.

send may be called as often as the product likes for as long as the card is there, which is the whole difference between a card and a picture. Return what should run when it leaves, or a promise of it when deciding what to draw takes a round trip.

type CardDrawHandler = (send: (face: RendererNode) => void, render: CardRender) => CardCleanup | Promise<CardCleanup>

type ChatBotRegistrationResult

Result of registering a bot ("New" | "Exists"). Re-exported from @parity/truapi.

type ChatBotRegistrationResult = ChatBotRegistrationStatus

type ChatCustomMessageRenderingRequestHandler

Product callback that streams native renderer trees for one custom message.

type ChatCustomMessageRenderingRequestHandler = (request: ChatCustomMessageRenderingRequest) => ObservableSource<RendererNode>

type 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 = HostChatActionSubscribeItem

type ChatRoom

type ChatRoom = Codec<ChatRoom>

type ChatRoomRegistrationResult

Result of registering a chat room: its status ("New" | "Exists") and the roomId the host derived from the room’s roomIdSource. Every later call names the room with that roomId. Re-exported from @parity/truapi.

type ChatRoomRegistrationResult = HostChatCreateRoomResponse

type ContextualAlias

A contextual alias obtained from Ring VRF.

Proves account membership in a ring without revealing which account.

Derived from @parity/truapi’s ContextualAlias, with both fields decoded to bytes.

type ContextualAlias = { [K in keyof WireAlias]: Uint8Array }

type DerivationIndex

Account selector within a product subtree. Encodes as Either<u32, [u8; 32]> on the wire (Index = left, Raw = right).

Index is the primary form — plain indices keep a product’s accounts enumerable. Raw carries a raw 32-byte derivation index for cases where bytes are genuinely necessary. Hosts expand Index(n) to the internal 32-byte index (u32 little-endian plus the index magic).

type DerivationIndex = Codec<DerivationIndex>

type DerivationIndex

Account selector within a product subtree. Encodes as Either<u32, [u8; 32]> on the wire (Index = left, Raw = right).

Index is the primary form — plain indices keep a product’s accounts enumerable. Raw carries a raw 32-byte derivation index for cases where bytes are genuinely necessary. Hosts expand Index(n) to the internal 32-byte index (u32 little-endian plus the index magic).

type DerivationIndex = { tag: "Index"; value: number } | { tag: "Raw"; value: HexString }

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 = HostDevicePermissionRequest

type 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 = unknown

type FinishedNftPurseStatus

The final status of an NFT move operation.

type FinishedNftPurseStatus = Extract<NftPurseStatus, { tag: "Cleared" | "Incomplete" }>

type 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 HostChainIdentifier

Chain-role identifier. A closed protocol enum, not a free-form name. The host maps each role to the concrete chain of its configured environment.

type HostChainIdentifier = ChainIdentifier

type HostConnectionStatus

Connection lifecycle of the host channel: "connecting" while the client waits for the host, "connected" once the channel is established, "disconnected" outside a host container or after the channel closes.

Not the same concept as @parity/product-sdk-signer’s identically-shaped ConnectionStatus, which tracks a signer provider rather than the transport.

type HostConnectionStatus = ConnectionStatus

type HostErrorPayload

The error a host call puts on its Err channel — truapi’s canonical scale.CallErrorValue envelope. Denied / Unsupported / MalformedFrame / HostFailure are transport-level failures; Domain wraps the actual per-domain error in a versioned envelope, which formatHostError digs through when rendering.

This is the payload HostCallFailedError carries — not the error type consumers branch on.

type HostErrorPayload = scale.CallErrorValue<VersionedDomainError>

type HostNftPurseCreateChequeRequest

type HostNftPurseCreateChequeRequest = Codec<HostNftPurseCreateChequeRequest>

type HostNftPurseCreateItemsRequest

type HostNftPurseCreateItemsRequest = Codec<HostNftPurseCreateItemsRequest>

type HostNftPurseCreatePurseRequest

type HostNftPurseCreatePurseRequest = Codec<HostNftPurseCreatePurseRequest>

type HostNftPurseCreateReceiveKeyRequest

type HostNftPurseCreateReceiveKeyRequest = Codec<HostNftPurseCreateReceiveKeyRequest>

type HostNftPurseDepositRequest

type HostNftPurseDepositRequest = Codec<HostNftPurseDepositRequest>

type HostNftPurseListenOneTimePaymentItem

Stream item of listen_one_time_payment.

type HostNftPurseListenOneTimePaymentItem = Codec<HostNftPurseListenOneTimePaymentItem>

type HostNftPurseListenOneTimePaymentItem

Stream item of listen_one_time_payment.

type HostNftPurseListenOneTimePaymentItem = { tag: "Channel"; value: NftPursePaymentTransmissionChannel } | { tag: "Cheque"; value: NftPurseCheque }

type HostNftPurseListenOneTimePaymentRequest

type HostNftPurseListenOneTimePaymentRequest = Codec<HostNftPurseListenOneTimePaymentRequest>

type HostNftPurseListenPaymentInboxItem

Stream item of listen_payment_inbox.

type HostNftPurseListenPaymentInboxItem = Codec<HostNftPurseListenPaymentInboxItem>

type HostNftPurseListenPaymentInboxItem

Stream item of listen_payment_inbox.

type HostNftPurseListenPaymentInboxItem = { tag: "Channel"; value: NftPursePaymentTransmissionChannel } | { tag: "Cheques"; value: NftPurseCheque[] }

type HostNftPurseListenPaymentInboxRequest

type HostNftPurseListenPaymentInboxRequest = Codec<HostNftPurseListenPaymentInboxRequest>

type HostNftPurseListPursesRequest

type HostNftPurseListPursesRequest = Codec<HostNftPurseListPursesRequest>

type HostNftPurseObserveOperationStatusRequest

type HostNftPurseObserveOperationStatusRequest = Codec<HostNftPurseObserveOperationStatusRequest>

type HostNftPurseQueryPurseRequest

type HostNftPurseQueryPurseRequest = Codec<HostNftPurseQueryPurseRequest>

type HostNftPurseRebalancePurseRequest

type HostNftPurseRebalancePurseRequest = Codec<HostNftPurseRebalancePurseRequest>

type HostNftPurseRefundRequest

type HostNftPurseRefundRequest = Codec<HostNftPurseRefundRequest>

type HostNftPurseRefundResponse

type HostNftPurseRefundResponse = Codec<HostNftPurseRefundResponse>

type HostNftPurseRevokeChequeRequest

type HostNftPurseRevokeChequeRequest = Codec<HostNftPurseRevokeChequeRequest>

type HostNftPurseTransferItemRequest

type HostNftPurseTransferItemRequest = Codec<HostNftPurseTransferItemRequest>

type HostPaymentBalanceSubscribeItem

type HostPaymentBalanceSubscribeItem = Codec<HostPaymentBalanceSubscribeItem>

type HostPaymentStatusSubscribeItem

Payment lifecycle status pushed to subscribers.

Completed, Failed and ClaimedPartially are terminal, and stay readable after the payment ends.

See RFC 0006 .

type HostPaymentStatusSubscribeItem = Codec<HostPaymentStatusSubscribeItem>

type HostPaymentStatusSubscribeItem

Payment lifecycle status pushed to subscribers.

Completed, Failed and ClaimedPartially are terminal, and stay readable after the payment ends.

See RFC 0006 .

type HostPaymentStatusSubscribeItem = { tag: "Processing"; value?: undefined } | { tag: "Completed"; value?: undefined } | { tag: "Failed"; value: { reason: string } } | { tag: "ClaimedPartially"; value: { actualClaimed: bigint } }

type HostPaymentTopUpStatusSubscribeItem

Progress of a top-up. Claimed { finalized: true }, ClaimedPartially and NotClaimed are terminal, and stay readable after the top-up ends.

type HostPaymentTopUpStatusSubscribeItem = Codec<HostPaymentTopUpStatusSubscribeItem>

type HostPaymentTopUpStatusSubscribeItem

Progress of a top-up. Claimed { finalized: true }, ClaimedPartially and NotClaimed are terminal, and stay readable after the top-up ends.

type HostPaymentTopUpStatusSubscribeItem = { tag: "Detecting"; value?: undefined } | { tag: "Claiming"; value?: undefined } | { tag: "Claimed"; value: { finalized: boolean } } | { tag: "ClaimedPartially"; value: { actualClaimed: bigint } } | { tag: "NotClaimed"; value?: undefined }

type LocaleInfo

Host locale value. A { languageTag } struct re-exported from @parity/truapi.

type LocaleInfo = HostLocaleSubscribeItem

type NftPurseCheque

type NftPurseCheque = Codec<NftPurseCheque>

type NftPurseChequeDestination

Where a cheque’s items go.

type NftPurseChequeDestination = Codec<NftPurseChequeDestination>

type NftPurseChequeDestination

Where a cheque’s items go.

type NftPurseChequeDestination = { tag: "Ephemeral"; value: NftPurseReceiveKey } | { tag: "Static"; value: { chequeId: NftPurseChequeId; encryptionKey: X25519PublicKey } }

type NftPurseChequeId

Id of a cheque, and the idempotency key of its deposit.

type NftPurseChequeId = Codec<`0x${string}`>

type NftPurseChequeId

Id of a cheque, and the idempotency key of its deposit.

type NftPurseChequeId = HexString

type NftPurseChequeRecipient

The part of a destination the recipient needs to find its decryption key.

type NftPurseChequeRecipient = Codec<NftPurseChequeRecipient>

type NftPurseChequeRecipient

The part of a destination the recipient needs to find its decryption key.

type NftPurseChequeRecipient = { tag: "Ephemeral"; value: NftPurseReceiveKey } | { tag: "Static"; value?: undefined }

type NftPurseClearedItem

type NftPurseClearedItem = Codec<NftPurseClearedItem>

type NftPurseClearingReference

type NftPurseClearingReference = Codec<NftPurseClearingReference>

type NftPurseId

Id of an NFT purse. Ids are allocated in order from 0. The main purse, which every user has and Root owns, is u32::MAX.

type NftPurseId = Codec<number>

type NftPurseId

Id of an NFT purse. Ids are allocated in order from 0. The main purse, which every user has and Root owns, is u32::MAX.

type NftPurseId = number

type NftPurseIdempotencyKey

Key a product chooses for one chain operation. It is scoped to that product, which follows the operation with observe_operation_status.

type NftPurseIdempotencyKey = Codec<`0x${string}`>

type NftPurseIdempotencyKey

Key a product chooses for one chain operation. It is scoped to that product, which follows the operation with observe_operation_status.

type NftPurseIdempotencyKey = HexString

type NftPurseInfoPage

type NftPurseInfoPage = Codec<NftPurseInfoPage>

type NftPurseItemKey

Public key of one item in a purse. The host holds its secret.

type NftPurseItemKey = Codec<`0x${string}`>

type NftPurseItemKey

Public key of one item in a purse. The host holds its secret.

type NftPurseItemKey = HexString

type NftPurseOwner

Who owns an NFT purse.

type NftPurseOwner = Codec<NftPurseOwner>

type NftPurseOwner

Who owns an NFT purse.

type NftPurseOwner = { tag: "Product"; value: ProductId } | { tag: "Root"; value?: undefined }

type NftPursePaymentTransmissionChannel

Channel a receiver listens on for a cheque.

type NftPursePaymentTransmissionChannel = Codec<NftPursePaymentTransmissionChannel>

type NftPursePaymentTransmissionChannel

Channel a receiver listens on for a cheque.

type NftPursePaymentTransmissionChannel = unknown

type NftPursePurse

type NftPursePurse = Codec<NftPursePurse>

type NftPurseReceiveKey

One-time key a receiver hands to the sender to start a payment.

type NftPurseReceiveKey = Codec<`0x${string}`>

type NftPurseReceiveKey

One-time key a receiver hands to the sender to start a payment.

type NftPurseReceiveKey = HexString

type NftPurseStatus

Progress of an operation that moves items.

type NftPurseStatus = Codec<NftPurseStatus>

type NftPurseStatus

Progress of an operation that moves items.

type NftPurseStatus = { tag: "InProgress"; value?: undefined } | { tag: "Clearing"; value: { cleared: NftPurseClearedItem[] } } | { tag: "Cleared"; value: { cleared: NftPurseClearedItem[]; reference: NftPurseClearingReference } } | { tag: "Incomplete"; value: { cleared: NftPurseClearedItem[]; failed: NftPurseItemKey[]; reference: NftPurseClearingReference } }

type NotificationId

Host-assigned id for a scheduled notification — pass to NotificationManager.cancel. truapi 0.23 dropped the NotificationId alias and uses the underlying number inline; kept here as a named alias so this package’s public surface is unchanged.

type NotificationId = number

type 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: DerivationIndex } } | { tag: "PrivateKey"; value: { sr25519SecretKey: HexString } } | { tag: "Coins"; value: { sr25519SecretKeys: HexString[] } }

type PocketCard

type PocketCard = Codec<PocketCard>

type PocketCardAction

A press or a value change inside one of the product’s card faces.

renderer.actionSubscribe is the only way back from a card: the face is a one way stream, and this is what a clickAction or valueChangeAction named in the tree comes back as.

type PocketCardAction = HostRendererActionSubscribeItem

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, dotNsIdentifier kept as a plain string (the adapter brands it as the wire’s ProductId), and derivationIndex kept as the plain numeric index (the adapter wraps it into the wire’s tagged DerivationIndex selector).

type ProductAccount = Omit<WireProductAccount, "publicKey"> & { derivationIndex: number; dotNsIdentifier: string; publicKey: Uint8Array }

type ProductAccountId

type ProductAccountId = Codec<ProductAccountId>

type ProductAccountLookup

How callers address a product account: app identifier plus an optional index, defaulting to 0. A ProductAccount satisfies this, so an account from AccountsProvider.getProductAccount can be passed straight back in.

type ProductAccountLookup = unknown

type ProductId

A product identifier. Rust validates identifiers received by the host.

type ProductId = Codec<ProductId>

type ProductId

A product identifier. Rust validates identifiers received by the host.

type ProductId = string & { readonly [productIdBrand]: true }

type ProductProofContext

The product-scoped proof context ({ productId, suffix }), expanded by the host into the 32-byte context a proof or alias is bound to.

productId is the plain product identifier (e.g. "myapp.dot"). The wire types it as a branded ProductId; the adapter brands it at the boundary, so product code keeps passing strings.

type ProductProofContext = Omit<WireProductProofContext, "productId"> & { productId: string }

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 = HostPushNotificationRequest

type RegisteredRingVrfKey

Registered key metadata returned by the host.

type RegisteredRingVrfKey = Omit<WireRegisteredRingVrfKey, "handle" | "publicKey"> & { handle: RingVrfKeyHandle; publicKey?: RingVrfPublicKey }

type RemotePermission

One remote-operation permission requested by the product (RFC 0002).

ChainSubmit, PreimageSubmit, StatementSubmit and BalanceAccess 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, StatementSubmit and BalanceAccess 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 } | { tag: "BalanceAccess"; value?: undefined } | { tag: "NftPurseRead"; value: { owner: NftPurseOwner } }

type RemotePermissionItem

Legacy alias of RemotePermission, kept for back-compat with code that used the older name. Use either freely.

type RemotePermissionItem = RemotePermission

type RenderCleanup

What a render handler returns: what to run when the body leaves the screen.

undefined in place of void would reject the ordinary (request, send) => send(body), whose inferred return is void.

type RenderCleanup = () => void | void

type RenderContextTag

Which kind of body the host is asking for.

type RenderContextTag = RenderContext["tag"]

type RenderFailure

The reason carried on the interrupt channel when a body cannot be drawn.

type RenderFailure = CallErrorValue<VersionedProductRendererRenderError>

type RenderHandler

Draws one kind of body.

type RenderHandler = (request: ProductRendererRenderRequest, send: (body: RendererNode) => void, interrupt: (reason?: RenderFailure) => void) => RenderCleanup

type RingLocation

type RingLocation = Codec<RingLocation>

type RingVrfKeyDisclosure

How much of a registry entry the caller asks for.

type RingVrfKeyDisclosure = Codec<RingVrfKeyDisclosure>

type RingVrfKeyDisclosure

How much of a registry entry the caller asks for.

type RingVrfKeyDisclosure = "Anonymized" | "PublicKey"

type RingVrfKeyHandle

Opaque public name of a registered ring-VRF key.

Handles come from AccountsProvider.listRingVrfKeys; product code cannot construct one from a derivation index.

type RingVrfKeyHandle = unknown

type RingVRFProof

A Ring VRF proof plus the values needed to verify it downstream (e.g. against a precompile): the alias it commits to, and the ring member index / revision the proof was generated against.

Derived from @parity/truapi’s HostAccountCreateProofResponse, with the byte fields decoded.

type RingVRFProof = Omit<WireRingVRFProof, "proof" | "contextualAlias"> & { contextualAlias: ContextualAlias; proof: Uint8Array }

type RingVrfPublicKey

Ring-VRF member public key, decoded from the wire’s hex string.

type RingVrfPublicKey = Uint8Array

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 = RemoteStatementStoreSubscribeItem

type 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 = HostThemeSubscribeItem

type 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

type Topic = HexString

type 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 = TrUApiClient

Examples

const truApi = await getTruApi(); if (truApi) { await truApi.permissions.requestRemotePermission({ permission: { tag: "ChainSubmit", value: undefined }, }); await truApi.system.navigateTo({ url: "polkadot://settings" }); }

type VrfSignature

An sr25519 VRF signature: the pre-output and its DLEQ proof.

Derived from @parity/truapi’s VrfSignature, decoded to bytes.

type VrfSignature = { [K in keyof WireVrfSignature]: Uint8Array }

type VrfTranscriptItem

One append_message(label, value) call replayed against a VRF transcript. Merlin labels are ASCII by convention: use utf8ToBytes("round").

Derived from @parity/truapi’s VrfTranscriptItem, decoded to bytes.

type VrfTranscriptItem = { [K in keyof WireVrfTranscriptItem]: Uint8Array }

type WithDecodeError

A call’s declared Err channel, plus HostResponseDecodeError: any host reply can fail to decode if the host and the product’s @parity/truapi client are on different protocol versions, so every decoded call can surface it in addition to its own typed errors. A call the host never answers surfaces as its HostTimeoutError subclass.

type WithDecodeError = E | HostResponseDecodeError

type X25519PublicKey

X25519 public key for key agreement (RFC 0022).

type X25519PublicKey = Codec<`0x${string}`>

type X25519PublicKey

X25519 public key for key agreement (RFC 0022).

type X25519PublicKey = HexString

Variables

BULLETIN_RPCS

Bulletin Chain RPC endpoints per network environment. paseo (Paseo Next v2), previewnet (zombienet, a step ahead of paseo), and devnet (public Paseo testnet) are populated today; polkadot and kusama are reserved for when those Bulletin deployments go live.

let BULLETIN_RPCS: { readonly devnet: readonly ["wss://bulletin-paseo.tservices.es:8443"]; readonly kusama: string[]; readonly paseo: readonly ["wss://paseo-bulletin-next-rpc.polkadot.io"]; readonly polkadot: string[]; readonly previewnet: readonly ["wss://previewnet.substrate.dev/bulletin"] } = ...

DEFAULT_BULLETIN_ENDPOINT

Default Bulletin Chain endpoint — the first entry under BULLETIN_RPCS.paseo.

let DEFAULT_BULLETIN_ENDPOINT: string = ...

MAIN_NFT_PURSE_ID

ID of the main purse. Its owner is Root, which means that no product owns it. A product needs a permission from the host to use it.

let MAIN_NFT_PURSE_ID: NftPurseId = 0xffff_ffff

NFT_PURSE_MAX_ITEMS_PER_CALL

The max number of items that one createItems call can create.

let NFT_PURSE_MAX_ITEMS_PER_CALL: 1000 = 1000

NFT_PURSE_MAX_NAME_BYTES

The max length of a purse name, in UTF-8 bytes.

let NFT_PURSE_MAX_NAME_BYTES: 64 = 64

NFT_PURSE_MAX_PAGE_SIZE

The max number of items in one queryPurse page.

let NFT_PURSE_MAX_PAGE_SIZE: 100 = 100