@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 |
HostUnavailableError | The host API is not available — the app is running outside a Polkadot host |
Functions
| Name | Summary |
|---|---|
broadcastTransaction() | Broadcast a signed transaction to the network via the host. |
createHostLocalStorage() | Construct a host-backed HostLocalStorage instance. Retained for API |
createHostPreimageManager() | Construct a PreimageManager. Retained for API compatibility; with the single |
createProofAuthorized() | Have the host sign a Statement using the product’s allowance-bearing account, |
deriveEntropy() | Derive deterministic entropy from a context key (RFC-0007). |
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
| 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. |
HostChainDiscovery | The host’s configured environment plus per-identifier resolved genesis hashes. |
HostLocalStorage | Persistent storage exposed by the host container, including string, JSON |
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 |
LocaleProvider | Host locale provider handle. subscribeLocale(callback) receives a typed |
NotificationManager | Host notification manager handle. Exposes push(input) (resolves to a |
PaymentManager | Payment manager handle. Exposes balance subscription, top-up, payment |
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 |
ProductProofContext | A product-scoped proof context: a product and a context within it. |
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 |
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 ("New" | "Exists"). Re-exported from @parity/truapi. |
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. |
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 |
HostPaymentBalanceSubscribeItem | — |
HostPaymentStatusSubscribeItem | Payment lifecycle status pushed to subscribers. |
HostPaymentStatusSubscribeItem | Payment lifecycle status pushed to subscribers. |
LocaleInfo | Host locale value. A { languageTag } struct re-exported from |
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, |
ProductProofContext | — |
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 |
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. |
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.
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 HostUnavailableError
The host API is not available — the app is running outside a Polkadot host
container (no injected TruAPI transport). The dominant case during local
development. Branch with instanceof HostUnavailableError to surface an
“open this app in a Polkadot host” message.
Extends: HostError
Constructors
constructor
new HostUnavailableError(message: string = "Host API is not available"): HostUnavailableErrorFunctions
broadcastTransaction()
Broadcast a signed transaction to the network via the host.
Calls truApi.chain.broadcastTransaction and unwraps the response. The host
keeps re-broadcasting until the transaction is finalized/dropped or
stopTransaction is called with the returned operation id.
broadcastTransaction(genesisHash: `0x${string}`, transaction: `0x${string}`): Promise<Result<string | null, HostError>>Parameters
genesisHash: The0x-prefixed genesis hash of the target chain.transaction: The0x-prefixed SCALE-encoded signed transaction.
Returns
ok with the operation id to pass to stopTransaction (or
null if the host accepted the broadcast without issuing one), or
err(HostUnavailableError | HostCallFailedError).
Examples
import { broadcastTransaction, stopTransaction } from "@parity/product-sdk-host";
const r = await broadcastTransaction(genesisHash, signedTx);
// later, to stop re-broadcasting:
if (r.ok && r.value) await stopTransaction(genesisHash, r.value);createHostLocalStorage()
Construct a host-backed HostLocalStorage instance. Retained for API
compatibility; with the single cached TruAPI client this is equivalent to
getHostLocalStorage.
createHostLocalStorage(): Promise<HostLocalStorage | null>Returns
A HostLocalStorage instance, or null if unavailable.
createHostPreimageManager()
Construct a PreimageManager. Retained for API compatibility; with the single
cached TruAPI client this is equivalent to getPreimageManager.
createHostPreimageManager(): Promise<PreimageManager | null>Returns
A PreimageManager instance, or null if unavailable.
createProofAuthorized()
Have the host sign a Statement using the product’s allowance-bearing account, which it picks internally — RFC-10 §“Statement Store allowance”. No per-call account id is needed (this is the sponsored-submission path).
Pairs with getStatementStore’s submit: call this to obtain a proof,
attach it to the Statement, and submit the result.
createProofAuthorized(statement: Statement): Promise<Result<StatementProof, HostError>>Parameters
statement: The Statement to be signed.
Returns
ok with the proof to attach before submitting, or
err(HostUnavailableError | HostCallFailedError).
deriveEntropy()
Derive deterministic entropy from a context key (RFC-0007).
The host derives entropy from the user’s wallet + the provided context key. Calling with the same key on the same wallet yields the same bytes; different keys (or different wallets) yield uncorrelated entropy.
deriveEntropy(key: Uint8Array): Promise<Result<Uint8Array<ArrayBufferLike>, HostError>>Parameters
key: Context key bytes (typically a SCALE-encoded discriminator).
Returns
ok with the derived entropy bytes, or
err(HostUnavailableError | HostCallFailedError).
Examples
import { deriveEntropy } from "@parity/product-sdk-host";
const r = await deriveEntropy(new TextEncoder().encode("my-app:seed-v1"));
if (r.ok) { const seed = r.value; }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
}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’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(): booleannavigateTo()
Ask the host to navigate to a URL (deep link or external link).
Calls truApi.system.navigateTo and unwraps the response. The host resolves
the destination itself — a dot-suffixed deep link (e.g.
"https://search.dot") routes to another app/route inside the container, an
https:// URL opens externally.
navigateTo(url: string): Promise<Result<void, HostError>>Parameters
url: The URL to navigate to.
Returns
ok on success, or err: HostUnavailableError if the host
is unavailable, or HostCallFailedError if it denies the navigation
(NavigateToErr::PermissionDenied) or fails otherwise (NavigateToErr::Unknown).
Examples
import { navigateTo } from "@parity/product-sdk-host";
const r = await navigateTo("https://search.dot");
if (!r.ok) handle(r.error);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): 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 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): PolkadotSignergetProductAccount
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): PolkadotSignergetUserId
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<ChatRoomRegistrationStatus>sendMessage
sendMessage(roomId: string, payload: ChatMessageContent): Promise<{ messageId: string }>subscribeAction
subscribeAction(callback: (action: HostChatActionSubscribeItem) => void): HostSubscriptionsubscribeChatList
subscribeChatList(callback: (rooms: ChatRoom[]) => void): HostSubscriptioninterface ChatRoom
A chat room the product participates in.
Properties
participatingAs
ChatRoomParticipationRoomHost or Bot.
roomId
stringRoom identifier.
interface 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 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
numberVersion 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): 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 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 NotificationManager
Host notification manager handle. Exposes push(input) (resolves to a
NotificationId) and cancel(id).
Methods
cancel
cancel(id: number): Promise<void>push
push(input: HostPushNotificationRequest): Promise<number>interface PaymentManager
Payment manager handle. Exposes balance subscription, top-up, payment requests, and payment-status subscription.
The balance / status / top-up-source shapes are @parity/truapi’s
HostPaymentBalanceSubscribeItem, HostPaymentStatusSubscribeItem, and
PaymentTopUpSource — used directly rather than re-aliased.
Methods
requestPayment
requestPayment(amount: bigint, destination: `0x${string}`, from?: number): Promise<{ id: string }>subscribeBalance
subscribeBalance(callback: (balance: HostPaymentBalanceSubscribeItem) => void, purse?: number): HostSubscriptionsubscribePaymentStatus
subscribePaymentStatus(paymentId: string, callback: (status: HostPaymentStatusSubscribeItem) => void): HostSubscriptiontopUp
topUp(amount: bigint, source: PaymentTopUpSource, into?: number): Promise<void>interface 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
stringA 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
stringdotNS product identifier (e.g. "my-product.dot") scoping the context.
suffix
DerivationIndexSelector 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): 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): HostSubscriptionType Aliases
type AllocatableResource
A resource the host can pre-allocate on behalf of the product (RFC 0010).
For the slot-table allowances (StatementStoreAllowance,
BulletinAllowance, SmartContractAllowance), pre-allocation is
opportunistic and the host may also fulfil the allowance implicitly on the
first submission. AutoSigning must be requested explicitly through this
call.
type AllocatableResource = Codec<AllocatableResource>type AllocatableResource
A resource the host can pre-allocate on behalf of the product (RFC 0010).
For the slot-table allowances (StatementStoreAllowance,
BulletinAllowance, SmartContractAllowance), pre-allocation is
opportunistic and the host may also fulfil the allowance implicitly on the
first submission. AutoSigning must be requested explicitly through this
call.
type AllocatableResource = { tag: "StatementStoreAllowance"; value?: undefined } | { tag: "BulletinAllowance"; value?: undefined } | { tag: "SmartContractAllowance"; value: 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 ("New" | "Exists"). Re-exported from @parity/truapi.
type ChatRoomRegistrationResult = ChatRoomRegistrationStatustype ContextualAlias
A contextual alias obtained from Ring VRF.
Proves account membership in a ring without revealing which account.
Derived from @parity/truapi’s 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 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 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 = HostLocaleSubscribeItemtype 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 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 = 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, and StatementSubmit are also triggered
implicitly by the corresponding business calls when not yet granted.
type RemotePermission = Codec<RemotePermission>type RemotePermission
One remote-operation permission requested by the product (RFC 0002).
ChainSubmit, PreimageSubmit, and StatementSubmit are also triggered
implicitly by the corresponding business calls when not yet granted.
type RemotePermission = { tag: "Remote"; value: { domains: string[] } } | { tag: "WebRtc"; value?: undefined } | { tag: "ChainSubmit"; value?: undefined } | { tag: "PreimageSubmit"; value?: undefined } | { tag: "StatementSubmit"; value?: undefined }type RemotePermissionItem
Legacy alias of RemotePermission, kept for back-compat with code that
used the older name. Use either freely.
type RemotePermissionItem = RemotePermissiontype 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.
type WithDecodeError = E | HostResponseDecodeErrorVariables
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 = ...