Skip to Content
API ReferencehostOverview

@parity/product-sdk-host

Detect and talk to the Polkadot Desktop/Mobile host container.

Use isInsideContainer to branch behavior when running embedded vs. standalone, and getHostLocalStorage, getHostProvider, and getStatementStore to reach the storage, signer, and statement-store APIs the host injects.

npm install @parity/product-sdk-host

Exports

Classes

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

Functions

NameSummary
broadcastTransaction()Broadcast a signed transaction to the network via the host.
createHostLocalStorage()Construct a host-backed HostLocalStorage instance. Retained for API
createHostPreimageManager()Construct a PreimageManager. Retained for API compatibility; with the single
createProofAuthorized()Have the host sign a Statement using the product’s allowance-bearing account,
deriveEntropy()Derive deterministic entropy from a context key (RFC-0007).
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
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.
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
navigateTo()Ask the host to navigate to a URL (deep link or external link).
registerRenderContext()Claim one render context on this client.
renderFailure()Build the reason, so a refusal reaches the host instead of dying here.
requestDevicePermission()Request a single device permission (camera, microphone, etc.) from the
requestPermission()Request a single remote permission from the host.
requestResourceAllocation()Request the host to pre-allocate one or more resource allowances.
stopTransaction()Stop an in-flight broadcast started by broadcastTransaction.
subscribeConnectionStatus()Subscribe to host-channel connection status. The callback fires synchronously
toHex()Convert bytes to a 0x-prefixed lower-case hex string.

Interfaces

NameSummary
AccountsProviderAccounts provider handle, backed by truApi.account.* / truApi.signing.*.
CardDrawRegistrationHandle for one card’s registration.
ChainPropertiesChain SS58/token properties as reported by the host’s
ChainSpecCombined chain-spec view returned by getChainSpec.
ChatCustomMessageRenderingRegistrationRegistration returned by the custom-message renderer channel.
ChatCustomMessageRenderingRequestRequest delivered when the host needs a native tree for a stored custom message.
ChatManagerChat manager handle. Exposes room/bot registration, message sending, and
ChatRoomA chat room the product participates in.
HostChainDiscoveryThe host’s configured environment plus per-identifier resolved genesis hashes.
HostLocalStoragePersistent storage exposed by the host container, including string, JSON
HostPaymentBalanceSubscribeItemCurrent payment balance state pushed to subscribers.
HostSignerOptionsTransaction settings for host-backed signers.
HostStatementStoreStatement Store handle exposed by the host container, backed by
HostSubscriptionSubscription handle returned by the host. Exposes unsubscribe() plus an
LocaleProviderHost locale provider handle. subscribeLocale(callback) receives a typed
NotificationManagerHost notification manager handle. Exposes push(input) (resolves to a
PaymentManagerPayment manager handle. Exposes balance subscription, top-up, payment
PocketCardOne of the calling product’s Pocket cards.
PocketManagerPocket manager handle.
PreimageManagerPreimage manager handle for bulletin chain operations, backed by
ProductAccountIdIdentifies a product-specific account by combining a dotNS domain name with a
ProductProofContextA product-scoped proof context: a product and a context within it.
RendererManagerRenderer manager handle.
RenderRegistrationHandle for one claimed context.
ResultAsyncNeverthrow-style ResultAsync returned by product-sdk methods.
RingLocationLocates a ring for ring VRF operations using only identifiers that are
SignedStatementA statement with a required (not optional) proof.
StatementA statement with optional proof and metadata.
ThemeProviderHost theme provider handle. subscribeTheme(callback) receives a typed

Type Aliases

NameSummary
AllocatableResourceA resource the host can pre-allocate on behalf of the product (RFC 0010).
AllocatableResourceA resource the host can pre-allocate on behalf of the product (RFC 0010).
AllocationOutcomeOutcome of allocating a single resource (RFC 0010).
AllocationOutcomeOutcome of allocating a single resource (RFC 0010).
CardCleanupWhat a card’s handler returns: what to run when the card leaves the screen.
CardDrawHandlerCalled when the host puts a card on screen, with the sink to draw into.
ChatBotRegistrationResultResult of registering a bot ("New" | "Exists"). Re-exported from @parity/truapi.
ChatCustomMessageRenderingRequestHandlerProduct callback that streams native renderer trees for one custom message.
ChatMessageContentContent of a chat message — one of several types.
ChatMessageContentContent of a chat message — one of several types.
ChatReceivedActionAction received via ChatManager.subscribeAction ({ roomId, peer, payload }). Re-exported from @parity/truapi.
ChatRoom—
ChatRoomRegistrationResultResult of registering a chat room ("New" | "Exists"). Re-exported from @parity/truapi.
ContextualAliasA contextual alias obtained from Ring VRF.
DerivationIndexAccount selector within a product subtree. Encodes as
DerivationIndexAccount selector within a product subtree. Encodes as
DevicePermissionKindDevice permission the dapp can ask the host to grant via
FeatureA feature the host can be probed for via featureSupported.
HexStringHex-encoded byte string, e.g. "0xdeadbeef".
HostAccountOne of the user’s existing wallet accounts, surfaced through the host and
HostChainIdentifierChain-role identifier. A closed protocol enum, not a free-form name. The
HostConnectionStatusConnection lifecycle of the host channel: "connecting" while the client waits
HostErrorPayloadThe error a host call puts on its Err channel — truapi’s canonical
HostPaymentBalanceSubscribeItem—
HostPaymentStatusSubscribeItemPayment lifecycle status pushed to subscribers.
HostPaymentStatusSubscribeItemPayment lifecycle status pushed to subscribers.
LocaleInfoHost locale value. A { languageTag } struct re-exported from
NotificationIdHost-assigned id for a scheduled notification — pass to
PaymentTopUpSourceSource for a payment top-up operation.
PaymentTopUpSourceSource for a payment top-up operation.
PocketCard—
PocketCardActionA press or a value change inside one of the product’s card faces.
ProductAccountA product account — an app-scoped derived account managed by the host wallet.
ProductAccountId—
ProductAccountLookupHow callers address a product account: app identifier plus an optional index,
ProductProofContext—
PushNotificationErrorPush notification error.
PushNotificationErrorPush notification error.
PushNotificationInputPush payload: text, an optional deeplink, and an optional scheduledAt
RegisteredRingVrfKeyRegistered key metadata returned by the host.
RemotePermissionOne remote-operation permission requested by the product (RFC 0002).
RemotePermissionOne remote-operation permission requested by the product (RFC 0002).
RemotePermissionItemLegacy alias of RemotePermission, kept for back-compat with code that
RenderCleanupWhat a render handler returns: what to run when the body leaves the screen.
RenderContextTagWhich kind of body the host is asking for.
RenderFailureThe reason carried on the interrupt channel when a body cannot be drawn.
RenderHandlerDraws one kind of body.
RingLocation—
RingVrfKeyDisclosureHow much of a registry entry the caller asks for.
RingVrfKeyDisclosureHow much of a registry entry the caller asks for.
RingVrfKeyHandleOpaque public name of a registered ring-VRF key.
RingVRFProofA Ring VRF proof plus the values needed to verify it downstream (e.g.
RingVrfPublicKeyRing-VRF member public key, decoded from the wire’s hex string.
SignedStatement—
Statement—
StatementProofCryptographic proof for a statement.
StatementProofCryptographic proof for a statement.
StatementsPageA page of signed statements delivered by HostStatementStore.subscribe.
StatementTopicFilterTopic-based subscription filter. The host delivers statements that match
ThemeModeHost theme value. A { name, variant } struct re-exported from
ThemeNameIdentifies a named theme.
ThemeNameIdentifies a named theme.
ThemeVariantLight or dark variant.
ThemeVariantLight or dark variant.
Topic—
TruApiThe TruApi client — namespaced access to every host protocol domain
VrfSignatureAn sr25519 VRF signature: the pre-output and its DLEQ proof.
VrfTranscriptItemOne append_message(label, value) call replayed against a VRF transcript.
WithDecodeErrorA call’s declared Err channel, plus HostResponseDecodeError: any

Variables

NameSummary
BULLETIN_RPCSBulletin Chain RPC endpoints per network environment. paseo (Paseo Next v2),
DEFAULT_BULLETIN_ENDPOINTDefault Bulletin Chain endpoint — the first entry under BULLETIN_RPCS.paseo.

Re-exports

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

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

Classes

class ChainNotSupportedError

Thrown by getHostProvider when the host container is reachable but does not support the requested chain — e.g. the chain isn’t enabled in this host build, or the descriptor’s genesis hash has drifted from the host’s after a network reset.

Surfacing this as a thrown error (rather than handing back a provider that silently swallows every JSON-RPC request) is what lets callers of createChainClient detect the failure. Without it, the host’s fallback no-op provider drops every request on the floor and queries await forever.

Extends: Error

Constructors

constructor
new ChainNotSupportedError(genesisHash: string): ChainNotSupportedError

Properties

genesisHash
propertyreadonlystring

Genesis hash of the chain the host refused, for programmatic detection.

class HostCallFailedError

A host call reached the container but failed on the Err channel. Wraps the structured truapi HostErrorPayload as payload (also preserved as cause); the message is rendered via formatHostError.

Extends: HostError

Constructors

constructor
new HostCallFailedError(label: string, payload: HostErrorPayload): HostCallFailedError

Properties

payload
propertyreadonlyHostErrorPayload

class HostError

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

Extends: Error

Implements: SdkError

Constructors

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

Properties

isSdkError
propertyreadonlytrue

Discriminant present on all SDK errors.

source
propertyreadonly"host"

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

class HostResponseDecodeError

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

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

Extends: HostError

Constructors

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

Properties

call
propertyreadonlystring

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

class HostUnavailableError

The host API is not available — the app is running outside a Polkadot host container (no injected TruAPI transport). The dominant case during local development. Branch with instanceof HostUnavailableError to surface an “open this app in a Polkadot host” message.

Extends: HostError

Constructors

constructor
new HostUnavailableError(message: string = "Host API is not available"): HostUnavailableError

Functions

broadcastTransaction()

Broadcast a signed transaction to the network via the host.

Calls truApi.chain.broadcastTransaction and unwraps the response. The host keeps re-broadcasting until the transaction is finalized/dropped or stopTransaction is called with the returned operation id.

broadcastTransaction(genesisHash: `0x${string}`, transaction: `0x${string}`): Promise<Result<string | null, HostError>>

Parameters

  • genesisHash: The 0x-prefixed genesis hash of the target chain.
  • transaction: The 0x-prefixed SCALE-encoded signed transaction.

Returns

ok with the operation id to pass to stopTransaction (or null if the host accepted the broadcast without issuing one), or err(HostUnavailableError | HostCallFailedError).

Examples

import { broadcastTransaction, stopTransaction } from "@parity/product-sdk-host"; const r = await broadcastTransaction(genesisHash, signedTx); // later, to stop re-broadcasting: if (r.ok && r.value) await stopTransaction(genesisHash, r.value);

createHostLocalStorage()

Construct a host-backed HostLocalStorage instance. Retained for API compatibility; with the single cached TruAPI client this is equivalent to getHostLocalStorage.

createHostLocalStorage(): Promise<HostLocalStorage | null>

Returns

A HostLocalStorage instance, or null if unavailable.

createHostPreimageManager()

Construct a PreimageManager. Retained for API compatibility; with the single cached TruAPI client this is equivalent to getPreimageManager.

createHostPreimageManager(): Promise<PreimageManager | null>

Returns

A PreimageManager instance, or null if unavailable.

createProofAuthorized()

Have the host sign a Statement using the product’s allowance-bearing account, which it picks internally — RFC-10 §“Statement Store allowance”. No per-call account id is needed (this is the sponsored-submission path).

Pairs with getStatementStore’s submit: call this to obtain a proof, attach it to the Statement, and submit the result.

createProofAuthorized(statement: Statement): Promise<Result<StatementProof, HostError>>

Parameters

  • statement: The Statement to be signed.

Returns

ok with the proof to attach before submitting, or err(HostUnavailableError | HostCallFailedError).

deriveEntropy()

Derive deterministic entropy from a context key (RFC-0007).

The host derives entropy from the user’s wallet + the provided context key. Calling with the same key on the same wallet yields the same bytes; different keys (or different wallets) yield uncorrelated entropy.

deriveEntropy(key: Uint8Array): Promise<Result<Uint8Array<ArrayBufferLike>, HostError>>

Parameters

  • key: Context key bytes (typically a SCALE-encoded discriminator).

Returns

ok with the derived entropy bytes, or err(HostUnavailableError | HostCallFailedError).

Examples

import { deriveEntropy } from "@parity/product-sdk-host"; const r = await deriveEntropy(new TextEncoder().encode("my-app:seed-v1")); if (r.ok) { const seed = r.value; }

featureSupported()

Probe the host for support of a specific feature.

Calls truApi.system.featureSupported, unwraps the response, and returns the host’s boolean answer.

featureSupported(feature: Feature): Promise<Result<boolean, HostError>>

Parameters

  • feature: The feature to probe for.

Returns

ok(true) if the host supports the feature, ok(false) otherwise, or err(HostUnavailableError | HostCallFailedError).

Examples

import { featureSupported } from "@parity/product-sdk-host"; const r = await featureSupported({ tag: "Chain", value: genesisHash }); if (r.ok && r.value) { ... }

findRingVrfKeyHandle()

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

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

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

formatHostError()

Extract a human-readable message from a host-side error.

Renders the HostErrorPayload shapes @parity/truapi surfaces. Accepts unknown because it is also the catch-all formatter for thrown adapter-method Error messages, so it falls back to Error/string/JSON rendering for anything that isn’t a recognized host error payload.

Used by HostCallFailedError to render its message, and by the throwing adapter-method helper unwrapHostResult.

formatHostError(error: unknown): string

fromHex()

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

fromHex(hex: string): Uint8Array

getAccountsProvider()

Get the accounts provider for managing host accounts, backed by truApi.account.* / truApi.signing.*. Returns null when running outside a host container.

getAccountsProvider(): Promise<AccountsProvider | null>

Returns

The accounts provider, or null if unavailable.

getChainSpec()

Fetch a chain’s full spec (genesis hash, name, and properties) from the host in one call.

Issues the three underlying chain.getSpec* requests concurrently, unwraps each response, and parses the properties JSON. Note the genesisHash in the result is the value the host echoes back from getSpecGenesisHash for the looked-up chain — pass the chain’s known genesis hash as the lookup key.

null (outside a container) is preserved as an ok value — it is an expected state, not a failure — so callers branch on r.ok && r.value. A real host-call failure surfaces on the err channel.

getChainSpec(genesisHash: `0x${string}`): Promise<Result<ChainSpec | null, HostError>>

Parameters

  • genesisHash: The 0x-prefixed genesis hash identifying the chain.

Returns

ok(spec) with the combined ChainSpec, ok(null) if the host is unavailable (running outside a container), or err(HostCallFailedError) if any underlying host call fails.

Examples

import { getChainSpec } from "@parity/product-sdk-host"; const r = await getChainSpec(genesisHash); if (r.ok && r.value) { console.log(r.value.name, r.value.properties?.tokenSymbol); }

getChatManager()

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

getChatManager(): Promise<ChatManager | null>

Returns

The chat manager, or null if unavailable.

Examples

import { getChatManager } from "@parity/product-sdk-host"; const chat = await getChatManager(); if (chat) { await chat.registerBot({ botId: "echo", name: "Echo Bot", icon: "" }); chat.subscribeAction((action) => { ... }); }

getHostChainInfo()

Resolve chain roles against the current host.

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

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

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

getHostLocalStorage()

Get the Host API localStorage instance when running inside a container. Returns null outside a container or when the host transport is unavailable.

getHostLocalStorage(): Promise<HostLocalStorage | null>

getHostProvider()

Get a PAPI-compatible JSON-RPC provider that routes through the host connection.

When running inside a Polkadot container, this builds a JsonRpcProvider over truApi.chain.* (see module:papi-provider), enabling shared connections and efficient routing. Returns null when not running inside a container.

getHostProvider(genesisHash: `0x${string}`): Promise<JsonRpcProvider | null>

Parameters

  • genesisHash: Genesis hash of the target chain (0x-prefixed hex string).

Returns

A host-routed JsonRpcProvider, or null if unavailable.

Throws

  • When inside a container but the host can’t serve the chain — surfaced instead of returning a provider that would hang forever.

getLocaleProvider()

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

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

getLocaleProvider(): Promise<LocaleProvider | null>

Returns

The locale provider, or null if unavailable.

Examples

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

getNotificationManager()

Get the host notification manager, backed by truApi.notifications.*. Returns null when running outside a host container.

getNotificationManager(): Promise<NotificationManager | null>

Returns

The notification manager, or null if unavailable.

Examples

import { getNotificationManager, type PushNotificationError } from "@parity/product-sdk-host"; const notifications = await getNotificationManager(); if (notifications) { try { const id = await notifications.push({ text: "Doors open in 1h", scheduledAt: someUnixMs, }); // later: await notifications.cancel(id); } catch (err) { const cause = (err as Error).cause as PushNotificationError | undefined; if (cause?.tag === "ScheduleLimitReached") { // host hit its pending-notification cap — surface to the user } } }

getPaymentManager()

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

getPaymentManager(): Promise<PaymentManager | null>

Returns

The payment manager, or null if unavailable.

Examples

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

isChainSupported()

Convenience probe: is the chain with the given genesis hash supported by the host? Wraps featureSupported for the Chain feature variant.

isChainSupported(genesisHash: `0x${string}`): Promise<Result<boolean, HostError>>

Parameters

  • genesisHash: The chain’s 0x-prefixed genesis hash.

Returns

ok(true) if the host supports the chain, ok(false) otherwise, or err(HostUnavailableError | HostCallFailedError).

Examples

import { isChainSupported } from "@parity/product-sdk-host"; const r = await isChainSupported(genesisHash); if (!r.ok || !r.value) { tellUserChainUnavailable(); }

isHostError()

Check whether a value is any HostError.

isHostError(error: unknown): error is HostError

isInsideContainer()

Detect if running inside a Host container (Polkadot Browser / Polkadot Desktop).

The SDK is designed to run exclusively inside a host container. This function is primarily useful for early validation or informational purposes.

isInsideContainer(): Promise<boolean>

isInsideContainerSync()

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

isInsideContainerSync(): boolean

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

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", handler: RenderHandler): RenderRegistration

renderFailure()

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

renderFailure(reason: string): RenderFailure

requestDevicePermission()

Request a single device permission (camera, microphone, etc.) from the host.

Calls truApi.permissions.requestDevicePermission and returns the host’s boolean granted/denied outcome.

requestDevicePermission(permission: HostDevicePermissionRequest): Promise<Result<boolean, HostError>>

Parameters

  • permission: The device permission to request.

Returns

ok(true) if the host granted the permission, ok(false) if denied, or err(HostUnavailableError | HostCallFailedError).

Examples

const r = await requestDevicePermission("Camera"); if (!r.ok || !r.value) { showCameraDeniedMessage(); }

requestPermission()

Request a single remote permission from the host.

Calls truApi.permissions.requestRemotePermission and returns the host’s boolean granted/denied outcome.

requestPermission(permission: RemotePermission): Promise<Result<boolean, HostError>>

Parameters

  • permission: The remote permission to request.

Returns

ok(true) if the host granted the permission, ok(false) if denied, or err(HostUnavailableError | HostCallFailedError).

Examples

const r = await requestPermission({ tag: "ChainSubmit", value: undefined }); if (!r.ok || !r.value) { tellUserToReconnect(); }

requestResourceAllocation()

Request the host to pre-allocate one or more resource allowances.

The host prompts the user once; subsequent operations covered by the granted allowance don’t re-prompt.

requestResourceAllocation(resources: AllocatableResource[]): Promise<Result<AllocationOutcome[], HostError>>

Parameters

  • resources: Resources to request.

Returns

ok with per-resource outcomes in the same order as resources, or err(HostUnavailableError | HostCallFailedError).

Examples

const r = await requestResourceAllocation([ { tag: "BulletinAllowance", value: undefined }, ]); if (r.ok && r.value[0] === "Allocated") { ... }

stopTransaction()

Stop an in-flight broadcast started by broadcastTransaction.

Calls truApi.chain.stopTransaction and unwraps the response.

stopTransaction(genesisHash: `0x${string}`, operationId: string): Promise<Result<void, HostError>>

Parameters

  • genesisHash: The 0x-prefixed genesis hash of the target chain.
  • operationId: The operation id returned by broadcastTransaction.

Returns

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

Examples

await stopTransaction(genesisHash, operationId);

subscribeConnectionStatus()

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

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

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

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

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

toHex()

Convert bytes to a 0x-prefixed lower-case hex string.

toHex(bytes: Uint8Array): `0x${string}`

Interfaces

interface AccountsProvider

Accounts provider handle, backed by truApi.account.* / truApi.signing.*. Surfaces the user’s wallet accounts, app-scoped product accounts, Ring VRF, user identity, connection status, and PolkadotSigner factories.

Lookup methods return a neverthrow ResultAsync (use .match(ok, err)); the signer factories return a synchronous PAPI PolkadotSigner. 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 for the case where the host’s reply cannot be decoded at all (a host/client protocol-version skew) — 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 PolkadotSigner for one of the user’s existing wallet accounts. name is accepted for callsite ergonomics but unused — the signer is derived from publicKey alone.

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

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

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

Build a PolkadotSigner for a product account. Signing routes through the host’s createTransaction path: the host decodes the metadata and forwards the opaque signed-extension bytes, so unknown extensions survive end-to-end.

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

List an owner’s registered ring-VRF keys.

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

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

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

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

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

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

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

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

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

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

The caller owns four things the types cannot enforce:

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

Hosts predating the call reject it through the error channel.

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

interface CardDrawRegistration

Handle for one card’s registration.

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

Methods

unsubscribe
unsubscribe(): void

interface ChainProperties

Chain SS58/token properties as reported by the host’s chainSpecProperties call.

The host returns this as a JSON string (mirroring the substrate chainSpec_v1_properties JSON-RPC, whose payload is an open-ended object). getChainSpec parses it into ChainSpec.properties and also surfaces the untouched JSON as ChainSpec.propertiesRaw. The well-known substrate fields are typed for convenience; the index signature keeps any chain-specific extras reachable without any at the call site.

Properties

ss58Format
propertyoptionalnumber

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

tokenDecimals
propertyoptionalnumber | number[]

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

tokenSymbol
propertyoptionalstring | string[]

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

interface ChainSpec

Combined chain-spec view returned by getChainSpec.

Properties

genesisHash
property`0x${string}`

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

name
propertystring

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

properties
propertyChainProperties | null

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

propertiesRaw
propertystring

The untouched JSON string the host returned for properties.

interface ChatCustomMessageRenderingRegistration

Registration returned by the custom-message renderer channel.

Methods

unsubscribe
unsubscribe(): void

interface ChatCustomMessageRenderingRequest

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

Properties

messageId
propertystring
messageType
propertystring
payload
propertyUint8Array

Methods

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

interface ChatManager

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

Methods

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

interface ChatRoom

A chat room the product participates in.

Properties

participatingAs
propertyChatRoomParticipation

RoomHost or Bot.

roomId
propertystring

Room identifier.

interface HostChainDiscovery

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

Properties

chains
propertyPartial<Record<HostChainIdentifier, HexString>>

Present for every requested identifier the host serves.

network
propertystring

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

interface HostLocalStorage

Persistent storage exposed by the host container, including string, JSON and raw byte (readBytes/writeBytes) accessors. Most apps reach it indirectly through the Storage package’s KvStore; reach for it directly via getHostLocalStorage when you need raw host storage without the KV abstraction.

Backed by truApi.localStorage.* (raw read/write/clear over hex bytes); getHostLocalStorage adapts that into this richer surface. readString resolves to "" for a missing key and readJSON/readBytes to null/undefined.

Methods

clear

Remove a key.

clear(key: string): Promise<void>
readBytes

Read raw bytes; undefined when the key is absent.

readBytes(key: string): Promise<Uint8Array<ArrayBufferLike> | undefined>
readJSON

Read and JSON-parse a value; null when the key is absent.

readJSON(key: string): Promise<unknown>
readString

Read a UTF-8 string value; "" when the key is absent.

readString(key: string): Promise<string>
writeBytes

Write raw bytes.

writeBytes(key: string, value: Uint8Array): Promise<void>
writeJSON

JSON-stringify and write a value.

writeJSON(key: string, value: unknown): Promise<void>
writeString

Write a UTF-8 string value.

writeString(key: string, value: string): Promise<void>

interface HostPaymentBalanceSubscribeItem

Current payment balance state pushed to subscribers.

See RFC 0006 .

Properties

available
propertybigint

Balance that can be spent right now.

interface HostSignerOptions

Transaction settings for host-backed signers.

Properties

txExtVersion
propertyoptionalnumber

Version used to encode the supplied transaction extensions. Defaults to 0.

interface HostStatementStore

Statement Store handle exposed by the host container, backed by truApi.statementStore.*. subscribe streams matching statements; createProofAuthorized signs a statement with the product’s RFC-10 allowance account (the sponsored path — no per-call account id); submit publishes a signed statement. The statement-store package layers a higher-level client on top.

Methods

createProofAuthorized
createProofAuthorized(statement: Statement): Promise<StatementProof>
submit
submit(signedStatement: SignedStatement): Promise<void>
subscribe
subscribe(filter: StatementTopicFilter, callback: (page: RemoteStatementStoreSubscribeItem) => void): HostSubscription

interface HostSubscription

Subscription handle returned by the host. Exposes unsubscribe() plus an onInterrupt hook that fires if the host interrupts the subscription server-side; onInterrupt returns a function that cancels the hook.

Methods

onInterrupt
onInterrupt(callback: (reason?: unknown) => void): () => void
unsubscribe
unsubscribe(): void

interface LocaleProvider

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

Methods

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

interface NotificationManager

Host notification manager handle. Exposes push(input) (resolves to a NotificationId) and cancel(id).

Methods

cancel
cancel(id: number): Promise<void>
push
push(input: HostPushNotificationRequest): Promise<number>

interface PaymentManager

Payment manager handle. Exposes balance subscription, top-up, payment requests, and payment-status subscription.

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

Methods

requestPayment
requestPayment(amount: bigint, destination: `0x${string}`, from?: number): Promise<{ id: string }>
subscribeBalance
subscribeBalance(callback: (balance: HostPaymentBalanceSubscribeItem) => void, purse?: number): HostSubscription
subscribePaymentStatus
subscribePaymentStatus(paymentId: string, callback: (status: HostPaymentStatusSubscribeItem) => void): HostSubscription
topUp
topUp(amount: bigint, source: PaymentTopUpSource, into?: number): Promise<void>

interface PocketCard

One of the calling product’s Pocket cards.

Properties

cardId
propertystring

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

privileged
propertyboolean

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

interface PocketManager

Pocket manager handle.

Methods

drawCard

Draw cardId whenever the host puts it on screen.

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

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

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

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

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

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

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

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

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

interface PreimageManager

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

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

Methods

lookup
lookup(key: `0x${string}`, callback: (preimage: Uint8Array<ArrayBufferLike> | null) => void): HostSubscription
submit
submit(value: Uint8Array): Promise<`0x${string}`>

interface ProductAccountId

Identifies a product-specific account by combining a dotNS domain name with a derivation index.

Properties

derivationIndex
propertyDerivationIndex

Account selector within the product subtree.

dotNsIdentifier
propertystring

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

interface ProductProofContext

A product-scoped proof context: a product and a context within it.

Hashed (with a product/<product_id>/ prefix) into the 32-byte context bound to a ring VRF proof, so contexts cannot collide across products and the same member key under different contexts yields unlinkable aliases.

Properties

productId
propertystring

dotNS product identifier (e.g. "my-product.dot") scoping the context.

suffix
propertyDerivationIndex

Selector distinguishing contexts within the product; expands to the same 32-byte derivation index as [ProductAccountId::derivation_index].

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", handler: RenderHandler): RenderRegistration

interface RenderRegistration

Handle for one claimed context.

Methods

unsubscribe
unsubscribe(): void

interface ResultAsync

Neverthrow-style ResultAsync returned by product-sdk methods.

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

Properties

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

interface RingLocation

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

Properties

chainId
property`0x${string}`

Genesis hash of the chain hosting the ring.

junctions
propertyRingLocationJunction[]

Path addressing the ring within the chain.

interface SignedStatement

A statement with a required (not optional) proof.

Properties

channel
propertyoptional`0x${string}`

Optional channel.

data
propertyoptional`0x${string}`

Optional data payload.

decryptionKey
propertyoptional`0x${string}`

Optional decryption key.

expiry
propertyoptionalbigint

Optional Unix timestamp expiry.

proof
propertyStatementProof

Required cryptographic proof.

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

[u8; 32] tags.

interface Statement

A statement with optional proof and metadata.

Properties

channel
propertyoptional`0x${string}`

Optional channel.

data
propertyoptional`0x${string}`

Optional data payload.

decryptionKey
propertyoptional`0x${string}`

Optional decryption key.

expiry
propertyoptionalbigint

Optional Unix timestamp expiry.

proof
propertyoptionalStatementProof

Optional cryptographic proof.

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

[u8; 32] tags.

interface ThemeProvider

Host theme provider handle. subscribeTheme(callback) receives a typed ThemeMode on every change and returns a HostSubscription.

Methods

subscribeTheme
subscribeTheme(callback: (theme: HostThemeSubscribeItem) => void): HostSubscription

Type Aliases

type AllocatableResource

A resource the host can pre-allocate on behalf of the product (RFC 0010).

For the slot-table allowances (StatementStoreAllowance, BulletinAllowance, SmartContractAllowance), pre-allocation is opportunistic and the host may also fulfil the allowance implicitly on the first submission. AutoSigning must be requested explicitly through this call.

type AllocatableResource = Codec<AllocatableResource>

type AllocatableResource

A resource the host can pre-allocate on behalf of the product (RFC 0010).

For the slot-table allowances (StatementStoreAllowance, BulletinAllowance, SmartContractAllowance), pre-allocation is opportunistic and the host may also fulfil the allowance implicitly on the first submission. AutoSigning must be requested explicitly through this call.

type AllocatableResource = { tag: "StatementStoreAllowance"; value?: undefined } | { tag: "BulletinAllowance"; value?: undefined } | { tag: "SmartContractAllowance"; value: DerivationIndex } | { tag: "AutoSigning"; value?: undefined }

type AllocationOutcome

Outcome of allocating a single resource (RFC 0010).

type AllocationOutcome = Codec<AllocationOutcome>

type AllocationOutcome

Outcome of allocating a single resource (RFC 0010).

type AllocationOutcome = "Allocated" | "Rejected" | "NotAvailable"

type CardCleanup

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

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

type CardCleanup = () => void | void

type CardDrawHandler

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

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

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

type ChatBotRegistrationResult

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

type ChatBotRegistrationResult = ChatBotRegistrationStatus

type ChatCustomMessageRenderingRequestHandler

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

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

type ChatMessageContent

Content of a chat message — one of several types.

type ChatMessageContent = Codec<ChatMessageContent>

type ChatMessageContent

Content of a chat message — one of several types.

type ChatMessageContent = { tag: "Text"; value: { text: string } } | { tag: "RichText"; value: ChatRichText } | { tag: "Actions"; value: ChatActions } | { tag: "File"; value: ChatFile } | { tag: "Reaction"; value: ChatReaction } | { tag: "ReactionRemoved"; value: ChatReaction } | { tag: "Custom"; value: ChatCustomMessage }

type ChatReceivedAction

Action received via ChatManager.subscribeAction ({ roomId, peer, payload }). Re-exported from @parity/truapi.

type ChatReceivedAction = HostChatActionSubscribeItem

type ChatRoom

type ChatRoom = Codec<ChatRoom>

type ChatRoomRegistrationResult

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

type ChatRoomRegistrationResult = ChatRoomRegistrationStatus

type ContextualAlias

A contextual alias obtained from Ring VRF.

Proves account membership in a ring without revealing which account.

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

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

type DerivationIndex

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

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

type DerivationIndex = Codec<DerivationIndex>

type DerivationIndex

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

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

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

type DevicePermissionKind

Device permission the dapp can ask the host to grant via requestDevicePermission. A string union ("Camera", "Microphone", …) re-exported from @parity/truapi.

type DevicePermissionKind = HostDevicePermissionRequest

type Feature

A feature the host can be probed for via featureSupported.

The only variant today is Chain, carrying the chain’s 0x-prefixed genesis hash. This is a flattened form of truapi’s HostFeatureSupportedRequest, which nests the hash as { tag: "Chain"; value: { genesisHash } } — we inline value as the HexString for ergonomics and re-nest it at the call site. New variants surface here as a widening of the union.

type Feature = unknown

type HexString

Hex-encoded byte string, e.g. "0xdeadbeef".

type HexString = `0x${string}`

type HostAccount

One of the user’s existing wallet accounts, surfaced through the host and identified by its public key and an optional name. Contrast with ProductAccount, which is also user-controlled but derived by the host for a specific app rather than picked from the user’s existing keys.

Derived from @parity/truapi’s LegacyAccount, with publicKey decoded to bytes.

type HostAccount = Omit<WireLegacyAccount, "publicKey"> & { publicKey: Uint8Array }

type HostChainIdentifier

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

type HostChainIdentifier = ChainIdentifier

type HostConnectionStatus

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

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

type HostConnectionStatus = ConnectionStatus

type HostErrorPayload

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

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

type HostErrorPayload = scale.CallErrorValue<VersionedDomainError>

type HostPaymentBalanceSubscribeItem

type HostPaymentBalanceSubscribeItem = Codec<HostPaymentBalanceSubscribeItem>

type HostPaymentStatusSubscribeItem

Payment lifecycle status pushed to subscribers.

Once a terminal state (Completed or Failed) is reached, the host delivers it and may close the subscription.

See RFC 0006 .

type HostPaymentStatusSubscribeItem = Codec<HostPaymentStatusSubscribeItem>

type HostPaymentStatusSubscribeItem

Payment lifecycle status pushed to subscribers.

Once a terminal state (Completed or Failed) is reached, the host delivers it and may close the subscription.

See RFC 0006 .

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

type LocaleInfo

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

type LocaleInfo = HostLocaleSubscribeItem

type NotificationId

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

type NotificationId = number

type PaymentTopUpSource

Source for a payment top-up operation.

See RFC 0006 .

type PaymentTopUpSource = Codec<PaymentTopUpSource>

type PaymentTopUpSource

Source for a payment top-up operation.

See RFC 0006 .

type PaymentTopUpSource = { tag: "ProductAccount"; value: { derivationIndex: DerivationIndex } } | { tag: "PrivateKey"; value: { sr25519SecretKey: HexString } } | { tag: "Coins"; value: { sr25519SecretKeys: HexString[] } }

type PocketCard

type PocketCard = Codec<PocketCard>

type PocketCardAction

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

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

type PocketCardAction = HostRendererActionSubscribeItem

type ProductAccount

A product account — an app-scoped derived account managed by the host wallet.

The host derives a unique keypair for each app (identified by dotNsIdentifier) so apps get their own account that the user controls but is scoped to the app.

Combines @parity/truapi’s ProductAccountId (the { dotNsIdentifier, derivationIndex } lookup key) with the ProductAccount payload, with publicKey decoded to bytes and derivationIndex kept as the plain numeric index (the adapter wraps it into the wire’s tagged DerivationIndex selector).

type ProductAccount = Omit<ProductAccountId, "derivationIndex"> & Omit<WireProductAccount, "publicKey"> & { derivationIndex: number; 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 = Omit<ProductAccountId, "derivationIndex"> & { derivationIndex?: number }

type ProductProofContext

type ProductProofContext = Codec<ProductProofContext>

type PushNotificationError

Push notification error.

type PushNotificationError = Codec<HostPushNotificationError>

type PushNotificationError

Push notification error.

type PushNotificationError = { tag: "ScheduleLimitReached"; value?: undefined } | { tag: "Unknown"; value: { reason: string } }

type PushNotificationInput

Push payload: text, an optional deeplink, and an optional scheduledAt (Unix timestamp in milliseconds; omit for immediate delivery). Re-exported from the truapi wire request type so the shape stays in lockstep with the protocol.

type PushNotificationInput = HostPushNotificationRequest

type RegisteredRingVrfKey

Registered key metadata returned by the host.

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

type RemotePermission

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

ChainSubmit, PreimageSubmit, and StatementSubmit are also triggered implicitly by the corresponding business calls when not yet granted.

type RemotePermission = Codec<RemotePermission>

type RemotePermission

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

ChainSubmit, PreimageSubmit, and StatementSubmit are also triggered implicitly by the corresponding business calls when not yet granted.

type RemotePermission = { tag: "Remote"; value: { domains: string[] } } | { tag: "WebRtc"; value?: undefined } | { tag: "ChainSubmit"; value?: undefined } | { tag: "PreimageSubmit"; value?: undefined } | { tag: "StatementSubmit"; value?: undefined }

type RemotePermissionItem

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

type RemotePermissionItem = RemotePermission

type RenderCleanup

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

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

type RenderCleanup = () => void | void

type RenderContextTag

Which kind of body the host is asking for.

type RenderContextTag = RenderContext["tag"]

type RenderFailure

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

type RenderFailure = CallErrorValue<VersionedProductRendererRenderError>

type RenderHandler

Draws one kind of body.

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

type RingLocation

type RingLocation = Codec<RingLocation>

type RingVrfKeyDisclosure

How much of a registry entry the caller asks for.

type RingVrfKeyDisclosure = Codec<RingVrfKeyDisclosure>

type RingVrfKeyDisclosure

How much of a registry entry the caller asks for.

type RingVrfKeyDisclosure = "Anonymized" | "PublicKey"

type RingVrfKeyHandle

Opaque public name of a registered ring-VRF key.

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

type RingVrfKeyHandle = unknown

type RingVRFProof

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

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

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

type RingVrfPublicKey

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

type RingVrfPublicKey = Uint8Array

type SignedStatement

type SignedStatement = Codec<SignedStatement>

type Statement

type Statement = Codec<Statement>

type StatementProof

Cryptographic proof for a statement.

type StatementProof = Codec<StatementProof>

type StatementProof

Cryptographic proof for a statement.

type StatementProof = { tag: "Sr25519"; value: { signature: HexString; signer: HexString } } | { tag: "Ed25519"; value: { signature: HexString; signer: HexString } } | { tag: "Ecdsa"; value: { signature: HexString; signer: HexString } } | { tag: "OnChain"; value: { blockHash: HexString; event: bigint; who: HexString } }

type StatementsPage

A page of signed statements delivered by HostStatementStore.subscribe.

truapi’s RemoteStatementStoreSubscribeItem, re-exported under a friendlier name. Pages arrive sequentially; isComplete is false while the host streams the historical backfill and true once it’s done (and on every subsequent live-update page).

type StatementsPage = RemoteStatementStoreSubscribeItem

type StatementTopicFilter

Topic-based subscription filter. The host delivers statements that match either all of the listed topics (matchAll) or any of them (matchAny).

This is a field-discriminated form of truapi’s RemoteStatementStoreSubscribeRequest, which is a tagged union ({ tag: "MatchAll"; value: Topic[] } | { tag: "MatchAny"; value: Topic[] }). The transport maps between the two.

type StatementTopicFilter = { matchAll: Topic[] } | { matchAny: Topic[] }

type ThemeMode

Host theme value. A { name, variant } struct re-exported from @parity/truapi.

type ThemeMode = HostThemeSubscribeItem

type ThemeName

Identifies a named theme.

type ThemeName = Codec<ThemeName>

type ThemeName

Identifies a named theme.

type ThemeName = { tag: "Custom"; value: string } | { tag: "Default"; value?: undefined }

type ThemeVariant

Light or dark variant.

type ThemeVariant = Codec<ThemeVariant>

type ThemeVariant

Light or dark variant.

type ThemeVariant = "Light" | "Dark"

type Topic

type Topic = HexString

type TruApi

The TruApi client — namespaced access to every host protocol domain (permissions, entropy, signing, statementStore, system, localStorage, …). Identical to TrUApiClient from @parity/truapi.

type TruApi = TrUApiClient

Examples

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

type VrfSignature

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

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

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

type VrfTranscriptItem

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

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

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

type WithDecodeError

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

type WithDecodeError = E | HostResponseDecodeError

Variables

BULLETIN_RPCS

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

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

DEFAULT_BULLETIN_ENDPOINT

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

let DEFAULT_BULLETIN_ENDPOINT: string = ...