@parity/product-sdk-host
Detect and talk to the Polkadot Desktop/Mobile host container.
Use isInsideContainer to branch behavior when running embedded vs. standalone,
and getHostLocalStorage, getHostProvider, and getStatementStore to reach
the storage, signer, and statement-store APIs the host injects.
npm install @parity/product-sdk-hostExports
Classes
| Name | Summary |
|---|---|
ChainNotSupportedError | Thrown by getHostProvider when the host container is reachable but does |
HostCallFailedError | A host call reached the container but failed on the Err channel. Wraps the |
HostError | Base class for all host errors. Use instanceof HostError (or isHostError) |
HostResponseDecodeError | A host call could not be processed to completion: the ResultAsync the |
HostTimeoutError | A host call got no answer before the truapi client’s deadline. The client |
HostUnavailableError | The host API is not available — the app is running outside a Polkadot host |
Functions
| Name | Summary |
|---|---|
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
| Name | Summary |
|---|---|
AccountsProvider | Accounts provider handle, backed by truApi.account.* / truApi.signing.*. |
CardDrawRegistration | Handle for one card’s registration. |
ChainProperties | Chain SS58/token properties as reported by the host’s |
ChainSpec | Combined chain-spec view returned by getChainSpec. |
ChatCustomMessageRenderingRegistration | Registration returned by the custom-message renderer channel. |
ChatCustomMessageRenderingRequest | Request delivered when the host needs a native tree for a stored custom message. |
ChatManager | Chat manager handle. Exposes room/bot registration, message sending, and |
ChatRoom | A chat room the product participates in. |
ChatSendMessageOptions | Options for ChatManager.sendMessage. |
HostChainDiscovery | The host’s configured environment plus per-identifier resolved genesis hashes. |
HostLocalStorage | Persistent storage exposed by the host container, including string, JSON |
HostNftPurseCreateChequeRequest | Request to hand items off in a cheque. |
HostNftPurseCreateItemsRequest | Request to create new item keys in a purse. |
HostNftPurseCreatePurseRequest | Request to create a purse owned by the caller. |
HostNftPurseCreateReceiveKeyRequest | Request for a one-time receive key. |
HostNftPurseDepositRequest | Request to deposit a received cheque. |
HostNftPurseListenOneTimePaymentRequest | Request to wait for a cheque sent to a receive key. |
HostNftPurseListenPaymentInboxRequest | Request to listen to one of the caller’s payment inboxes. |
HostNftPurseListPursesRequest | Request to list an owner’s purses. |
HostNftPurseObserveOperationStatusRequest | Request for the status of an operation the calling product registered. |
HostNftPurseQueryPurseRequest | Request for one page of a purse’s spendable items. |
HostNftPurseRebalancePurseRequest | Request to move items between purses. |
HostNftPurseRefundRequest | Request to return a deposited cheque’s items to their original keys. |
HostNftPurseRefundResponse | The refund’s moves, by the depositing purse’s item keys. |
HostNftPurseRevokeChequeRequest | Request to release the items of an undelivered cheque. |
HostNftPurseTransferItemRequest | Request to move one item to a key outside the purses. |
HostPaymentBalanceSubscribeItem | Current payment balance state pushed to subscribers. |
HostSignerOptions | Transaction settings for host-backed signers. |
HostStatementStore | Statement Store handle exposed by the host container, backed by |
HostSubscription | Subscription handle returned by the host. Exposes unsubscribe() plus an |
HostTxExtension | One extension as the host signs it. |
HostTxRequest | What the host needs to build and sign one transaction. |
LocaleProvider | Host locale provider handle. subscribeLocale(callback) receives a typed |
NftPurseCheque | Items handed off to a recipient. |
NftPurseClearedItem | One item an operation moved. |
NftPurseClearingReference | Product-visible clearing reference. |
NftPurseInfoPage | One page of the spendable items of a purse. |
NftPurseManager | The NFT purse calls of the host. A call that fails throws an Error with the |
NftPursePurse | A purse as list_purses reports it. |
NotificationManager | Host notification manager handle. Exposes push(input) (resolves to a |
PaymentManager | Payment manager handle. Exposes balance subscription, top-ups and payment |
PaymentRequest | A payment the product asks the user to approve: an id it chooses, the amount and the payee. |
PocketCard | One of the calling product’s Pocket cards. |
PocketManager | Pocket manager handle. |
PreimageManager | Preimage manager handle for bulletin chain operations, backed by |
ProductAccountId | Identifies a product-specific account by combining a dotNS domain name with a |
RendererManager | Renderer manager handle. |
RenderRegistration | Handle for one claimed context. |
ResultAsync | Neverthrow-style ResultAsync returned by product-sdk methods. |
RingLocation | Locates a ring for ring VRF operations using only identifiers that are |
SignedStatement | A statement with a required (not optional) proof. |
Statement | A statement with optional proof and metadata. |
ThemeProvider | Host theme provider handle. subscribeTheme(callback) receives a typed |
TopUpRequest | A top-up the product starts: an id it chooses, the amount and where the funds come from. |
Type Aliases
| Name | Summary |
|---|---|
AllocatableResource | A resource the host can pre-allocate on behalf of the product (RFC 0010). |
AllocatableResource | A resource the host can pre-allocate on behalf of the product (RFC 0010). |
AllocationOutcome | Outcome of allocating a single resource (RFC 0010). |
AllocationOutcome | Outcome of allocating a single resource (RFC 0010). |
CardCleanup | What a card’s handler returns: what to run when the card leaves the screen. |
CardDrawHandler | Called when the host puts a card on screen, with the sink to draw into. |
ChatBotRegistrationResult | Result of registering a bot ("New" | "Exists"). Re-exported from @parity/truapi. |
ChatCustomMessageRenderingRequestHandler | Product callback that streams native renderer trees for one custom message. |
ChatMessageContent | Content of a chat message — one of several types. |
ChatMessageContent | Content of a chat message — one of several types. |
ChatReceivedAction | Action received via ChatManager.subscribeAction ({ roomId, peer, payload }). Re-exported from @parity/truapi. |
ChatRoom | — |
ChatRoomRegistrationResult | Result of registering a chat room: its status ("New" | "Exists") and the |
ContextualAlias | A contextual alias obtained from Ring VRF. |
DerivationIndex | Account selector within a product subtree. Encodes as |
DerivationIndex | Account selector within a product subtree. Encodes as |
DevicePermissionKind | Device permission the dapp can ask the host to grant via |
Feature | A feature the host can be probed for via featureSupported. |
FinishedNftPurseStatus | The final status of an NFT move operation. |
HexString | Hex-encoded byte string, e.g. "0xdeadbeef". |
HostAccount | One of the user’s existing wallet accounts, surfaced through the host and |
HostChainIdentifier | Chain-role identifier. A closed protocol enum, not a free-form name. The |
HostConnectionStatus | Connection lifecycle of the host channel: "connecting" while the client waits |
HostErrorPayload | The error a host call puts on its Err channel — truapi’s canonical |
HostNftPurseCreateChequeRequest | — |
HostNftPurseCreateItemsRequest | — |
HostNftPurseCreatePurseRequest | — |
HostNftPurseCreateReceiveKeyRequest | — |
HostNftPurseDepositRequest | — |
HostNftPurseListenOneTimePaymentItem | Stream item of listen_one_time_payment. |
HostNftPurseListenOneTimePaymentItem | Stream item of listen_one_time_payment. |
HostNftPurseListenOneTimePaymentRequest | — |
HostNftPurseListenPaymentInboxItem | Stream item of listen_payment_inbox. |
HostNftPurseListenPaymentInboxItem | Stream item of listen_payment_inbox. |
HostNftPurseListenPaymentInboxRequest | — |
HostNftPurseListPursesRequest | — |
HostNftPurseObserveOperationStatusRequest | — |
HostNftPurseQueryPurseRequest | — |
HostNftPurseRebalancePurseRequest | — |
HostNftPurseRefundRequest | — |
HostNftPurseRefundResponse | — |
HostNftPurseRevokeChequeRequest | — |
HostNftPurseTransferItemRequest | — |
HostPaymentBalanceSubscribeItem | — |
HostPaymentStatusSubscribeItem | Payment lifecycle status pushed to subscribers. |
HostPaymentStatusSubscribeItem | Payment lifecycle status pushed to subscribers. |
HostPaymentTopUpStatusSubscribeItem | Progress of a top-up. Claimed { finalized: true }, ClaimedPartially and |
HostPaymentTopUpStatusSubscribeItem | Progress of a top-up. Claimed { finalized: true }, ClaimedPartially and |
LocaleInfo | Host locale value. A { languageTag } struct re-exported from |
NftPurseCheque | — |
NftPurseChequeDestination | Where a cheque’s items go. |
NftPurseChequeDestination | Where a cheque’s items go. |
NftPurseChequeId | Id of a cheque, and the idempotency key of its deposit. |
NftPurseChequeId | Id of a cheque, and the idempotency key of its deposit. |
NftPurseChequeRecipient | The part of a destination the recipient needs to find its decryption key. |
NftPurseChequeRecipient | The part of a destination the recipient needs to find its decryption key. |
NftPurseClearedItem | — |
NftPurseClearingReference | — |
NftPurseId | Id of an NFT purse. Ids are allocated in order from 0. The main purse, |
NftPurseId | Id of an NFT purse. Ids are allocated in order from 0. The main purse, |
NftPurseIdempotencyKey | Key a product chooses for one chain operation. It is scoped to that |
NftPurseIdempotencyKey | Key a product chooses for one chain operation. It is scoped to that |
NftPurseInfoPage | — |
NftPurseItemKey | Public key of one item in a purse. The host holds its secret. |
NftPurseItemKey | Public key of one item in a purse. The host holds its secret. |
NftPurseOwner | Who owns an NFT purse. |
NftPurseOwner | Who owns an NFT purse. |
NftPursePaymentTransmissionChannel | Channel a receiver listens on for a cheque. |
NftPursePaymentTransmissionChannel | Channel a receiver listens on for a cheque. |
NftPursePurse | — |
NftPurseReceiveKey | One-time key a receiver hands to the sender to start a payment. |
NftPurseReceiveKey | One-time key a receiver hands to the sender to start a payment. |
NftPurseStatus | Progress of an operation that moves items. |
NftPurseStatus | Progress of an operation that moves items. |
NotificationId | Host-assigned id for a scheduled notification — pass to |
PaymentTopUpSource | Source for a payment top-up operation. |
PaymentTopUpSource | Source for a payment top-up operation. |
PocketCard | — |
PocketCardAction | A press or a value change inside one of the product’s card faces. |
ProductAccount | A product account — an app-scoped derived account managed by the host wallet. |
ProductAccountId | — |
ProductAccountLookup | How callers address a product account: app identifier plus an optional index, |
ProductId | A product identifier. Rust validates identifiers received by the host. |
ProductId | A product identifier. Rust validates identifiers received by the host. |
ProductProofContext | The product-scoped proof context ({ productId, suffix }), expanded by the |
PushNotificationError | Push notification error. |
PushNotificationError | Push notification error. |
PushNotificationInput | Push payload: text, an optional deeplink, and an optional scheduledAt |
RegisteredRingVrfKey | Registered key metadata returned by the host. |
RemotePermission | One remote-operation permission requested by the product (RFC 0002). |
RemotePermission | One remote-operation permission requested by the product (RFC 0002). |
RemotePermissionItem | Legacy alias of RemotePermission, kept for back-compat with code that |
RenderCleanup | What a render handler returns: what to run when the body leaves the screen. |
RenderContextTag | Which kind of body the host is asking for. |
RenderFailure | The reason carried on the interrupt channel when a body cannot be drawn. |
RenderHandler | Draws one kind of body. |
RingLocation | — |
RingVrfKeyDisclosure | How much of a registry entry the caller asks for. |
RingVrfKeyDisclosure | How much of a registry entry the caller asks for. |
RingVrfKeyHandle | Opaque public name of a registered ring-VRF key. |
RingVRFProof | A Ring VRF proof plus the values needed to verify it downstream (e.g. |
RingVrfPublicKey | Ring-VRF member public key, decoded from the wire’s hex string. |
SignedStatement | — |
Statement | — |
StatementProof | Cryptographic proof for a statement. |
StatementProof | Cryptographic proof for a statement. |
StatementsPage | A page of signed statements delivered by HostStatementStore.subscribe. |
StatementTopicFilter | Topic-based subscription filter. The host delivers statements that match |
ThemeMode | Host theme value. A { name, variant } struct re-exported from |
ThemeName | Identifies a named theme. |
ThemeName | Identifies a named theme. |
ThemeVariant | Light or dark variant. |
ThemeVariant | Light or dark variant. |
Topic | — |
TruApi | The TruApi client — namespaced access to every host protocol domain |
VrfSignature | An sr25519 VRF signature: the pre-output and its DLEQ proof. |
VrfTranscriptItem | One append_message(label, value) call replayed against a VRF transcript. |
WithDecodeError | A call’s declared Err channel, plus HostResponseDecodeError: any |
X25519PublicKey | X25519 public key for key agreement (RFC 0022). |
X25519PublicKey | X25519 public key for key agreement (RFC 0022). |
Variables
| Name | Summary |
|---|---|
BULLETIN_RPCS | Bulletin Chain RPC endpoints per network environment. paseo (Paseo Next v2), |
DEFAULT_BULLETIN_ENDPOINT | Default Bulletin Chain endpoint — the first entry under BULLETIN_RPCS.paseo. |
MAIN_NFT_PURSE_ID | ID of the main purse. Its owner is Root, which means that no product owns |
NFT_PURSE_MAX_ITEMS_PER_CALL | The max number of items that one createItems call can create. |
NFT_PURSE_MAX_NAME_BYTES | The max length of a purse name, in UTF-8 bytes. |
NFT_PURSE_MAX_PAGE_SIZE | The max number of items in one queryPurse page. |
Re-exports
Convenience re-exports from leaf packages. Click through for the canonical documentation.
| Name | Kind | Source package |
|---|---|---|
err() | function | @parity/result |
isSdkError() | function | @parity/product-sdk-errors |
ok() | function | @parity/result |
Result | type | @parity/result |
SdkError | interface | @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): ChainNotSupportedErrorProperties
genesisHash
stringGenesis hash of the chain the host refused, for programmatic detection.
class HostCallFailedError
A host call reached the container but failed on the Err channel. Wraps the
structured truapi HostErrorPayload as payload (also preserved
as cause); the message is rendered via formatHostError.
Extends: HostError
Constructors
constructor
new HostCallFailedError(label: string, payload: HostErrorPayload): HostCallFailedErrorProperties
payload
HostErrorPayloadclass HostError
Base class for all host errors. Use instanceof HostError (or isHostError)
to catch any host-related failure. Implements the cross-package
SdkError marker so isSdkError(e) also recognizes it.
Extends: Error
Implements: SdkError
Constructors
constructor
new HostError(message: string, options?: ErrorOptions): HostErrorProperties
isSdkError
trueDiscriminant present on all SDK errors.
source
"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): HostResponseDecodeErrorProperties
call
stringThe 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): HostTimeoutErrorProperties
timeoutMs
numberHow 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"): HostUnavailableErrorFunctions
asProductId()
Designate a product identifier without changing or validating its value.
asProductId(value: string): ProductIdbroadcastTransaction()
Broadcast a signed transaction to the network via the host.
Calls truApi.chain.broadcastTransaction and unwraps the response. The host
keeps re-broadcasting until the transaction is finalized/dropped or
stopTransaction is called with the returned operation id.
broadcastTransaction(genesisHash: `0x${string}`, transaction: `0x${string}`): Promise<Result<string | null, HostError>>Parameters
genesisHash: The0x-prefixed genesis hash of the target chain.transaction: The0x-prefixed SCALE-encoded signed transaction.
Returns
ok with the operation id to pass to stopTransaction (or
null if the host accepted the broadcast without issuing one), or
err(HostUnavailableError | HostCallFailedError).
Examples
import { broadcastTransaction, stopTransaction } from "@parity/product-sdk-host";
const r = await broadcastTransaction(genesisHash, signedTx);
// later, to stop re-broadcasting:
if (r.ok && r.value) await stopTransaction(genesisHash, r.value);createHostLocalStorage()
Construct a host-backed HostLocalStorage instance. Retained for API
compatibility; with the single cached TruAPI client this is equivalent to
getHostLocalStorage.
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): CommonSignerTxCreatorParameters
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 | undefinedformatHostError()
Extract a human-readable message from a host-side error.
Renders the HostErrorPayload shapes @parity/truapi surfaces. Accepts
unknown because it is also the catch-all formatter for thrown adapter-method
Error messages, so it falls back to Error/string/JSON rendering for
anything that isn’t a recognized host error payload.
Used by HostCallFailedError to render its message, and by the throwing
adapter-method helper unwrapHostResult.
formatHostError(error: unknown): stringfromHex()
Convert a hex string (with or without 0x) to bytes.
fromHex(hex: string): Uint8ArraygetAccountsProvider()
Get the accounts provider for managing host accounts, backed by
truApi.account.* / truApi.signing.*. Returns null when running outside
a host container.
getAccountsProvider(): Promise<AccountsProvider | null>Returns
The accounts provider, or null if unavailable.
getChainSpec()
Fetch a chain’s full spec (genesis hash, name, and properties) from the host in one call.
Issues the three underlying chain.getSpec* requests concurrently, unwraps
each response, and parses the properties JSON. Note the genesisHash in the
result is the value the host echoes back from getSpecGenesisHash for the
looked-up chain — pass the chain’s known genesis hash as the lookup key.
null (outside a container) is preserved as an ok value — it is an
expected state, not a failure — so callers branch on r.ok && r.value. A
real host-call failure surfaces on the err channel.
getChainSpec(genesisHash: `0x${string}`): Promise<Result<ChainSpec | null, HostError>>Parameters
genesisHash: The0x-prefixed genesis hash identifying the chain.
Returns
ok(spec) with the combined ChainSpec, ok(null) if the
host is unavailable (running outside a container), or
err(HostCallFailedError) if any underlying host call fails.
Examples
import { getChainSpec } from "@parity/product-sdk-host";
const r = await getChainSpec(genesisHash);
if (r.ok && r.value) {
console.log(r.value.name, r.value.properties?.tokenSymbol);
}getChatManager()
Get the host chat manager, backed by truApi.chat.*. Returns null when
running outside a host container.
getChatManager(): Promise<ChatManager | null>Returns
The chat manager, or null if unavailable.
Examples
import { getChatManager } from "@parity/product-sdk-host";
const chat = await getChatManager();
if (chat) {
await chat.registerBot({ botId: "echo", name: "Echo Bot", icon: "" });
chat.subscribeAction((action) => { ... });
}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 | undefinedisChainSupported()
Convenience probe: is the chain with the given genesis hash supported by the
host? Wraps featureSupported for the Chain feature variant.
isChainSupported(genesisHash: `0x${string}`): Promise<Result<boolean, HostError>>Parameters
genesisHash: The chain’s0x-prefixed genesis hash.
Returns
ok(true) if the host supports the chain, ok(false) otherwise, or
err(HostUnavailableError | HostCallFailedError).
Examples
import { isChainSupported } from "@parity/product-sdk-host";
const r = await isChainSupported(genesisHash);
if (!r.ok || !r.value) {
tellUserChainUnavailable();
}isHostError()
Check whether a value is any HostError.
isHostError(error: unknown): error is HostErrorisInsideContainer()
Detect if running inside a Host container (Polkadot Browser / Polkadot Desktop).
The SDK is designed to run exclusively inside a host container. This function is primarily useful for early validation or informational purposes.
isInsideContainer(): Promise<boolean>isInsideContainerSync()
Host-container detection. true when a test client is injected, otherwise the
sandbox heuristic (iframe / webview marker / injected message port).
isInsideContainerSync(): booleanisNftPurseOperationFinished()
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 FinishedNftPurseStatusnavigateTo()
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): RenderRegistrationrenderFailure()
Build the reason, so a refusal reaches the host instead of dying here.
renderFailure(reason: string): RenderFailurerequestDevicePermission()
Request a single device permission (camera, microphone, etc.) from the host.
Calls truApi.permissions.requestDevicePermission and returns the host’s
boolean granted/denied outcome.
requestDevicePermission(permission: HostDevicePermissionRequest): Promise<Result<boolean, HostError>>Parameters
permission: The device permission to request.
Returns
ok(true) if the host granted the permission, ok(false) if denied,
or err(HostUnavailableError | HostCallFailedError).
Examples
const r = await requestDevicePermission("Camera");
if (!r.ok || !r.value) {
showCameraDeniedMessage();
}requestPermission()
Request a single remote permission from the host.
Calls truApi.permissions.requestRemotePermission and returns the host’s
boolean granted/denied outcome.
requestPermission(permission: RemotePermission): Promise<Result<boolean, HostError>>Parameters
permission: The remote permission to request.
Returns
ok(true) if the host granted the permission, ok(false) if denied,
or err(HostUnavailableError | HostCallFailedError).
Examples
const r = await requestPermission({ tag: "ChainSubmit", value: undefined });
if (!r.ok || !r.value) {
tellUserToReconnect();
}requestResourceAllocation()
Request the host to pre-allocate one or more resource allowances.
The host prompts the user once; subsequent operations covered by the granted allowance don’t re-prompt.
requestResourceAllocation(resources: AllocatableResource[]): Promise<Result<AllocationOutcome[], HostError>>Parameters
resources: Resources to request.
Returns
ok with per-resource outcomes in the same order as resources, or
err(HostUnavailableError | HostCallFailedError).
Examples
const r = await requestResourceAllocation([
{ tag: "BulletinAllowance", value: undefined },
]);
if (r.ok && r.value[0] === "Allocated") { ... }stopTransaction()
Stop an in-flight broadcast started by broadcastTransaction.
Calls truApi.chain.stopTransaction and unwraps the response.
stopTransaction(genesisHash: `0x${string}`, operationId: string): Promise<Result<void, HostError>>Parameters
genesisHash: The0x-prefixed genesis hash of the target chain.operationId: The operation id returned bybroadcastTransaction.
Returns
ok on success, or err(HostUnavailableError | HostCallFailedError).
Examples
await stopTransaction(genesisHash, operationId);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): () => voidtoHex()
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): CommonSignerTxCreatorgetProductAccount
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): CommonSignerTxCreatorgetUserId
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
AutoSigningallowance 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): HostSubscriptioninterface 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(): voidinterface ChainProperties
Chain SS58/token properties as reported by the host’s
chainSpecProperties call.
The host returns this as a JSON string (mirroring the substrate
chainSpec_v1_properties JSON-RPC, whose payload is an open-ended object).
getChainSpec parses it into ChainSpec.properties and also
surfaces the untouched JSON as ChainSpec.propertiesRaw. The well-known substrate fields are
typed for convenience; the index signature keeps any chain-specific extras
reachable without any at the call site.
Properties
ss58Format
numberAddress prefix used for SS58 encoding (e.g. 0 for Polkadot).
tokenDecimals
number | number[]Decimal places of the chain’s native token(s).
tokenSymbol
string | string[]Ticker symbol(s) of the chain’s native token(s).
interface ChainSpec
Combined chain-spec view returned by getChainSpec.
Properties
genesisHash
`0x${string}`The chain’s 0x-prefixed genesis hash, as reported by the host.
name
stringHuman-readable chain name (e.g. "Polkadot").
properties
ChainProperties | nullParsed chain properties, or null if the host’s JSON payload couldn’t
be parsed. Inspect propertiesRaw for the original string.
propertiesRaw
stringThe untouched JSON string the host returned for properties.
interface ChatCustomMessageRenderingRegistration
Registration returned by the custom-message renderer channel.
Methods
unsubscribe
unsubscribe(): voidinterface ChatCustomMessageRenderingRequest
Request delivered when the host needs a native tree for a stored custom message.
Properties
messageId
stringmessageType
stringpayload
Uint8ArrayMethods
subscribeActions
subscribeActions(callback: (actionId: string, payload: Uint8Array<ArrayBufferLike> | undefined) => void): VoidFunctioninterface ChatManager
Chat manager handle. Exposes room/bot registration, message sending, and subscription to the room list and incoming actions.
Methods
onCustomMessageRenderingRequest
onCustomMessageRenderingRequest(handler: ChatCustomMessageRenderingRequestHandler): ChatCustomMessageRenderingRegistrationregisterBot
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): HostSubscriptionsubscribeChatList
subscribeChatList(callback: (rooms: ChatRoom[]) => void): HostSubscriptioninterface ChatRoom
A chat room the product participates in.
Properties
participatingAs
ChatRoomParticipationRoomHost or Bot.
roomId
stringRoom identifier.
interface ChatSendMessageOptions
Options for ChatManager.sendMessage.
Properties
alt
stringOne 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
Partial<Record<HostChainIdentifier, HexString>>Present for every requested identifier the host serves.
network
stringEcosystem 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
numberSource purse.
items
`0x${string}`[]Items to hand off.
to
NftPurseChequeDestinationRecipient.
interface HostNftPurseCreateItemsRequest
Request to create new item keys in a purse.
Properties
count
numberNumber of keys, in 1..=1000.
purse
numberPurse that receives the keys.
interface HostNftPurseCreatePurseRequest
Request to create a purse owned by the caller.
Properties
name
stringPurse name, at most [NFT_PURSE_MAX_NAME_BYTES] bytes.
interface HostNftPurseCreateReceiveKeyRequest
Request for a one-time receive key.
Properties
into
numberPurse the received items go into.
interface HostNftPurseDepositRequest
Request to deposit a received cheque.
Properties
cheque
NftPurseChequeThe received cheque. Its id is the idempotency key.
to
numberPurse the items go into.
interface HostNftPurseListenOneTimePaymentRequest
Request to wait for a cheque sent to a receive key.
Properties
key
`0x${string}`Receive key from create_receive_key.
interface HostNftPurseListenPaymentInboxRequest
Request to listen to one of the caller’s payment inboxes.
Properties
inboxDomain
`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
NftPurseOwnerWhose purses.
interface HostNftPurseObserveOperationStatusRequest
Request for the status of an operation the calling product registered.
Properties
idempotencyKey
`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
numberZero-based page index.
pageSize
numberItems per page, in 1..=100.
purse
numberPurse to read.
interface HostNftPurseRebalancePurseRequest
Request to move items between purses.
Properties
from
numberSource purse.
idempotencyKey
`0x${string}`Names the operation for observe_operation_status.
keys
`0x${string}`[]Items to move.
to
numberDestination purse.
interface HostNftPurseRefundRequest
Request to return a deposited cheque’s items to their original keys.
Properties
chequeId
`0x${string}`The deposited cheque.
interface HostNftPurseRefundResponse
The refund’s moves, by the depositing purse’s item keys.
Properties
started
`0x${string}`[]Items whose move back to their cheque key started.
unavailable
`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
`0x${string}`Cheque to revoke.
interface HostNftPurseTransferItemRequest
Request to move one item to a key outside the purses.
Properties
destination
`0x${string}`Key that receives it.
idempotencyKey
`0x${string}`Names the operation for observe_operation_status.
item
`0x${string}`Item to move.
interface HostPaymentBalanceSubscribeItem
Current payment balance state pushed to subscribers.
See RFC 0006 .
Properties
available
bigintBalance that can be spent right now.
interface HostSignerOptions
Transaction settings for host-backed signers.
Properties
txExtVersion
numberPipeline 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): HostSubscriptioninterface HostSubscription
Subscription handle returned by the host. Exposes unsubscribe() plus an
onInterrupt hook that fires if the host interrupts the subscription
server-side; onInterrupt returns a function that cancels the hook.
Methods
onInterrupt
onInterrupt(callback: (reason?: unknown) => void): () => voidunsubscribe
unsubscribe(): voidinterface HostTxExtension
One extension as the host signs it.
Properties
additionalSigned
`0x${string}`extra
`0x${string}`id
stringinterface HostTxRequest
What the host needs to build and sign one transaction.
Properties
callData
`0x${string}`extensions
HostTxExtension[]genesisHash
`0x${string}`txExtVersion
numberinterface 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): HostSubscriptioninterface NftPurseCheque
Items handed off to a recipient.
Properties
encryptedSecrets
`0x${string}`Item secrets, encrypted to the recipient.
id
`0x${string}`Cheque id.
items
`0x${string}`[]Keys of the handed-off items.
recipient
NftPurseChequeRecipientWho can decrypt it.
version
numberCheque format version, 0.
interface NftPurseClearedItem
One item an operation moved.
Properties
consumed
`0x${string}`Source key, from the origin purse or from the cheque.
finalized
booleanWhether the moving transaction is finalized.
minted
`0x${string}`Destination key, in the destination purse.
interface NftPurseClearingReference
Product-visible clearing reference.
Properties
leaves
[`0x${string}`, `0x${string}`][]Source item key and the hash of the transaction that moved it, sorted by item key.
root
`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
booleanWhether a later page holds more items.
items
`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): HostSubscriptionlistenPaymentInbox
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): HostSubscriptionlistPurses
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): HostSubscriptionqueryPurse
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
numberPurse id.
name
stringName 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): HostSubscriptionsubscribePaymentStatus
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): HostSubscriptionsubscribeTopUpStatus
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): HostSubscriptiontopUp
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
bigintAmount in balance units. Zero is refused as InvalidAmount.
destination
`0x${string}`32-byte account the payment goes to.
from
numberPurse to pay from; omitted pays from the main purse.
id
`0x${string}`32-byte id. Reusing one is answered AlreadyExists.
interface PocketCard
One of the calling product’s Pocket cards.
Properties
cardId
stringCard label declared by the product, unique within the product.
privileged
booleanPlaced 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): CardDrawRegistrationremoveCard
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): HostSubscriptionsubscribeCards
The product’s cards, republished whenever the collection changes.
subscribeCards(callback: (cards: PocketCard[]) => void): HostSubscriptioninterface PreimageManager
Preimage manager handle for bulletin chain operations, backed by
truApi.preimage.*. lookup opens a HostSubscription (unsubscribe
onInterrupt) that delivers the preimage bytes — ornulluntil the host finds them;submituploads a preimage and resolves to its0x-prefixed hex key.
Methods
lookup
lookup(key: `0x${string}`, callback: (preimage: Uint8Array<ArrayBufferLike> | null) => void): HostSubscriptionsubmit
submit(value: Uint8Array): Promise<`0x${string}`>interface ProductAccountId
Identifies a product-specific account by combining a dotNS domain name with a derivation index.
Properties
derivationIndex
DerivationIndexAccount selector within the product subtree.
dotNsIdentifier
ProductIdA 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): RenderRegistrationinterface RenderRegistration
Handle for one claimed context.
Methods
unsubscribe
unsubscribe(): voidinterface ResultAsync
Neverthrow-style ResultAsync returned by product-sdk methods.
Use .match(onOk, onErr) to handle success/error cases.
Properties
match
(ok: (t: T) => A, err: (e: E) => B) => Promise<A | B>interface RingLocation
Locates a ring for ring VRF operations using only identifiers that are stable across membership changes.
Properties
chainId
`0x${string}`Genesis hash of the chain hosting the ring.
junctions
RingLocationJunction[]Path addressing the ring within the chain.
interface SignedStatement
A statement with a required (not optional) proof.
Properties
channel
`0x${string}`Optional channel.
data
`0x${string}`Optional data payload.
decryptionKey
`0x${string}`Optional decryption key.
expiry
bigintOptional Unix timestamp expiry.
proof
StatementProofRequired cryptographic proof.
topics
`0x${string}`[][u8; 32] tags.
interface Statement
A statement with optional proof and metadata.
Properties
channel
`0x${string}`Optional channel.
data
`0x${string}`Optional data payload.
decryptionKey
`0x${string}`Optional decryption key.
expiry
bigintOptional Unix timestamp expiry.
proof
StatementProofOptional cryptographic proof.
topics
`0x${string}`[][u8; 32] tags.
interface ThemeProvider
Host theme provider handle. subscribeTheme(callback) receives a typed
ThemeMode on every change and returns a HostSubscription.
Methods
subscribeTheme
subscribeTheme(callback: (theme: HostThemeSubscribeItem) => void): HostSubscriptioninterface TopUpRequest
A top-up the product starts: an id it chooses, the amount and where the funds come from.
Properties
amount
bigintAmount in balance units. Zero is refused as InvalidAmount.
id
`0x${string}`32-byte id. Reusing one is answered AlreadyExists.
into
numberPurse to credit; omitted credits the main purse.
source
PaymentTopUpSourceWhere 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 | voidtype 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 = ChatBotRegistrationStatustype 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 = HostChatActionSubscribeItemtype 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 = HostChatCreateRoomResponsetype 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 = HostDevicePermissionRequesttype Feature
A feature the host can be probed for via featureSupported.
The only variant today is Chain, carrying the chain’s 0x-prefixed genesis
hash. This is a flattened form of truapi’s HostFeatureSupportedRequest,
which nests the hash as { tag: "Chain"; value: { genesisHash } } — we
inline value as the HexString for ergonomics and re-nest it at the call
site. New variants surface here as a widening of the union.
type Feature = unknowntype 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 = ChainIdentifiertype 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 = ConnectionStatustype 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 = HostLocaleSubscribeItemtype 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 = HexStringtype 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 = numbertype 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 = HexStringtype 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 = HexStringtype 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 = unknowntype 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 = HexStringtype 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 = numbertype PaymentTopUpSource
Source for a payment top-up operation.
See RFC 0006 .
type PaymentTopUpSource = Codec<PaymentTopUpSource>type PaymentTopUpSource
Source for a payment top-up operation.
See RFC 0006 .
type PaymentTopUpSource = { tag: "ProductAccount"; value: { derivationIndex: 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 = HostRendererActionSubscribeItemtype 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 = unknowntype 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 = HostPushNotificationRequesttype 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 = RemotePermissiontype 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 | voidtype 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) => RenderCleanuptype 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 = unknowntype 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 = Uint8Arraytype SignedStatement
type SignedStatement = Codec<SignedStatement>type Statement
type Statement = Codec<Statement>type StatementProof
Cryptographic proof for a statement.
type StatementProof = Codec<StatementProof>type StatementProof
Cryptographic proof for a statement.
type StatementProof = { tag: "Sr25519"; value: { signature: HexString; signer: HexString } } | { tag: "Ed25519"; value: { signature: HexString; signer: HexString } } | { tag: "Ecdsa"; value: { signature: HexString; signer: HexString } } | { tag: "OnChain"; value: { blockHash: HexString; event: bigint; who: HexString } }type StatementsPage
A page of signed statements delivered by HostStatementStore.subscribe.
truapi’s RemoteStatementStoreSubscribeItem, re-exported under a friendlier
name. Pages arrive sequentially; isComplete is false while the host
streams the historical backfill and true once it’s done (and on every
subsequent live-update page).
type StatementsPage = RemoteStatementStoreSubscribeItemtype StatementTopicFilter
Topic-based subscription filter. The host delivers statements that match
either all of the listed topics (matchAll) or any of them (matchAny).
This is a field-discriminated form of truapi’s RemoteStatementStoreSubscribeRequest,
which is a tagged union ({ tag: "MatchAll"; value: Topic[] } | { tag: "MatchAny"; value: Topic[] }).
The transport maps between the two.
type StatementTopicFilter = { matchAll: Topic[] } | { matchAny: Topic[] }type ThemeMode
Host theme value. A { name, variant } struct re-exported from
@parity/truapi.
type ThemeMode = HostThemeSubscribeItemtype ThemeName
Identifies a named theme.
type ThemeName = Codec<ThemeName>type ThemeName
Identifies a named theme.
type ThemeName = { tag: "Custom"; value: string } | { tag: "Default"; value?: undefined }type ThemeVariant
Light or dark variant.
type ThemeVariant = Codec<ThemeVariant>type ThemeVariant
Light or dark variant.
type ThemeVariant = "Light" | "Dark"type Topic
type Topic = HexStringtype TruApi
The TruApi client — namespaced access to every host protocol domain
(permissions, entropy, signing, statementStore, system,
localStorage, …). Identical to TrUApiClient from @parity/truapi.
type TruApi = TrUApiClientExamples
const truApi = await getTruApi();
if (truApi) {
await truApi.permissions.requestRemotePermission({
permission: { tag: "ChainSubmit", value: undefined },
});
await truApi.system.navigateTo({ url: "polkadot://settings" });
}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 | HostResponseDecodeErrortype 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 = HexStringVariables
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_ffffNFT_PURSE_MAX_ITEMS_PER_CALL
The max number of items that one createItems call can create.
let NFT_PURSE_MAX_ITEMS_PER_CALL: 1000 = 1000NFT_PURSE_MAX_NAME_BYTES
The max length of a purse name, in UTF-8 bytes.
let NFT_PURSE_MAX_NAME_BYTES: 64 = 64NFT_PURSE_MAX_PAGE_SIZE
The max number of items in one queryPurse page.
let NFT_PURSE_MAX_PAGE_SIZE: 100 = 100