@parity/product-sdk-host 0.0.0-dev.312.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/papi-provider.ts","../src/truapi.ts","../src/container.ts","../src/chains.ts","../src/worker.ts","../src/chain-discovery.ts","../src/accounts.ts","../src/permissions.ts","../src/theme.ts","../src/entropy.ts","../src/chat.ts","../src/payments.ts","../src/notifications.ts","../src/navigation.ts","../src/features.ts","../src/chain-spec.ts","../src/chain-transaction.ts"],"names":["followSubscriptionId","log","createLogger"],"mappings":";;;;;;;;;;;AA0CA,SAAS,SAAS,KAAA,EAA2D;AACzE,EAAA,OACI,SAAS,IAAA,IACT,OAAO,UAAU,QAAA,IACjB,OAAQ,MAA4B,GAAA,KAAQ,QAAA;AAEpD;AAGA,SAAS,UAAU,KAAA,EAA6C;AAC5D,EAAA,OACI,SAAS,IAAA,IACT,OAAO,UAAU,QAAA,IACjB,OAAQ,MAA+B,MAAA,KAAW,QAAA;AAE1D;AAaO,SAAS,gBAAgB,KAAA,EAAwB;AACpD,EAAA,IAAI,KAAA,YAAiB,KAAA,EAAO,OAAO,KAAA,CAAM,OAAA;AACzC,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AAEtC,EAAA,IAAI,QAAA,CAAS,KAAK,CAAA,EAAG;AAEjB,IAAA,IAAI,KAAA,CAAM,GAAA,KAAQ,QAAA,IAAY,QAAA,CAAS,KAAA,CAAM,KAAK,CAAA,IAAK,KAAA,CAAM,KAAA,CAAM,KAAA,KAAU,MAAA,EAAW;AACpF,MAAA,OAAO,eAAA,CAAgB,KAAA,CAAM,KAAA,CAAM,KAAK,CAAA;AAAA,IAC5C;AAEA,IAAA,IAAI,SAAA,CAAU,KAAA,CAAM,KAAK,CAAA,EAAG;AACxB,MAAA,OAAO,GAAG,KAAA,CAAM,GAAG,CAAA,EAAA,EAAK,KA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AC/B,MAAM,UAAA,CAAW,KAAA;AAAA,IACjB,UAAA;AAAA,IACA;AAAA,GACH,CAAA;AACL;ACrHA,IAAMA,IAAAA,GAAMC,aAAa,wBAAwB,CAAA;AAwBjD,eAAsB,oBAAA,CAClB,aACA,WAAA,EACyC;AACzC,EAAA,MAAM,MAAA,GAAS,MAAM,SAAA,EAAU;AAC/B,EAAA,IAAI,CAAC,MAAA,EAAQ;AACT,IAAA,OAAO,GAAA,CAAI,IAAI,oBAAA,CAAqB,0CAA0C,CAAC,CAAA;AAAA,EACnF;AACA,EAAAD,IAAAA,CAAI,KAAA,CAAM,sBAAA,EAAwB,EAAE,aAAa,CAAA;AAEjD,EAAA,OAAO,aAAA;AAAA,IACH,OAAO,KAAA,CAAM,oBAAA,CAAqB,EAAE,WAAA,EAAa,aAAa,CAAA;AAAA,IAC9D,CAAC,QAAA,KAAa,QAAA,CAAS,WAAA,IAAe,IAAA;AAAA,IACtC;AAAA,GACJ;AACJ;AAiBA,eAAsB,eAAA,CAClB,aACA,WAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,MAAM,SAAA,EAAU;AAC/B,EAAA,IAAI,CAAC,MAAA,EAAQ;AACT,IAAA,OAAO,GAAA,CAAI,IAAI,oBAAA,CAAqB,qCAAqC,CAAC,CAAA;AAAA,EAC9E;AACA,EAAAA,KAAI,KAAA,CAAM,iBAAA,EAAmB,EAAE,WAAA,EAAa,aAAa,CAAA;AAEzD,EAAA,OAAO,aAAA;AAAA,IACH,OAAO,KAAA,CAAM,eAAA,CAAgB,EAAE,WAAA,EAAa,aAAa,CAAA;AAAA,IACzD,MAAM,MAAA;AAAA,IACN;AAAA,GACJ;AACJ","file":"index.js","sourcesContent":["// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Typed errors carried on the `err` channel of the host public API's\n * {@link Result} returns.\n *\n * The hierarchy mirrors `@parity/product-sdk-signer`'s error classes\n * (`HostUnavailableError` / `HostRejectedError`), so the two layers share one\n * idiom: branch with `instanceof`, and every error is a real `Error` with a\n * stack trace and `cause`. The structured truapi wire error\n * ({@link HostErrorPayload}) rides along as {@link HostCallFailedError.payload}\n * for callers that want fine-grained tag-level handling.\n *\n * This module also owns {@link HostErrorPayload} (the wire-error shape) and\n * {@link formatHostError} (renders a payload to a message) — co-located with the\n * error classes that consume them so the host error model lives in one place.\n *\n * @module\n */\nimport type { SdkError } from \"@parity/product-sdk-errors\";\nimport type { scale } from \"@parity/truapi\";\n\n/**\n * What a `Domain`-tagged call error carries. Widened from truapi's per-domain\n * `Versioned*Error` types (all `{ tag: \"V1\", value: <domain error> }` today)\n * so one payload type covers every call.\n */\ntype VersionedDomainError = { tag: string; value?: unknown };\n\n/**\n * The error a host call puts on its `Err` channel — truapi's canonical\n * {@link scale.CallErrorValue} envelope. `Denied` / `Unsupported` /\n * `MalformedFrame` / `HostFailure` are transport-level failures; `Domain`\n * wraps the actual per-domain error in a versioned envelope, which\n * {@link formatHostError} digs through when rendering.\n *\n * This is the payload {@link HostCallFailedError} carries — not the error\n * type consumers branch on.\n */\nexport type HostErrorPayload = scale.CallErrorValue<VersionedDomainError>;\n\n/** Narrow to a tagged-union member: `{ tag, value? }`. */\nfunction isTagged(value: unknown): value is { tag: string; value?: unknown } {\n return (\n value != null &&\n typeof value === \"object\" &&\n typeof (value as { tag?: unknown }).tag === \"string\"\n );\n}\n\n/** Narrow to a reason-carrying payload — truapi's `GenericError` shape. */\nfunction hasReason(value: unknown): value is { reason: string } {\n return (\n value != null &&\n typeof value === \"object\" &&\n typeof (value as { reason?: unknown }).reason === \"string\"\n );\n}\n\n/**\n * Extract a human-readable message from a host-side error.\n *\n * Renders the {@link HostErrorPayload} shapes `@parity/truapi` surfaces. Accepts\n * `unknown` because it is also the catch-all formatter for thrown adapter-method\n * `Error` messages, so it falls back to `Error`/string/JSON rendering for\n * anything that isn't a recognized host error payload.\n *\n * Used by {@link HostCallFailedError} to render its message, and by the throwing\n * adapter-method helper `unwrapHostResult`.\n */\nexport function formatHostError(error: unknown): string {\n if (error instanceof Error) return error.message;\n if (typeof error === \"string\") return error;\n\n if (isTagged(error)) {\n // `Domain` carries the real error inside a versioned envelope — unwrap it.\n if (error.tag === \"Domain\" && isTagged(error.value) && error.value.value !== undefined) {\n return formatHostError(error.value.value);\n }\n // Tagged variant carrying a reason: { tag, value: { reason } }\n if (hasReason(error.value)) {\n return `${error.tag}: ${error.value.reason}`;\n }\n // Unit tagged variant, e.g. { tag: \"Denied\" } / { tag: \"PermissionDenied\" }\n return error.tag;\n }\n // GenericError: { reason }\n if (hasReason(error)) {\n return error.reason;\n }\n\n if (error != null && typeof error === \"object\" && \"message\" in error) {\n const message = (error as { message: unknown }).message;\n if (typeof message === \"string\") return message;\n }\n\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n\n/**\n * Base class for all host errors. Use `instanceof HostError` (or {@link isHostError})\n * to catch any host-related failure. Implements the cross-package\n * {@link SdkError} marker so `isSdkError(e)` also recognizes it.\n */\nexport class HostError extends Error implements SdkError {\n readonly isSdkError = true as const;\n readonly source = \"host\";\n\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"HostError\";\n }\n}\n\n/**\n * The host API is not available — the app is running outside a Polkadot host\n * container (no injected TruAPI transport). The dominant case during local\n * development. Branch with `instanceof HostUnavailableError` to surface an\n * \"open this app in a Polkadot host\" message.\n */\nexport class HostUnavailableError extends HostError {\n constructor(message = \"Host API is not available\") {\n super(message);\n this.name = \"HostUnavailableError\";\n }\n}\n\n/**\n * A host call reached the container but failed on the `Err` channel. Wraps the\n * structured truapi {@link HostErrorPayload} as {@link payload} (also preserved\n * as `cause`); the message is rendered via {@link formatHostError}.\n */\nexport class HostCallFailedError extends HostError {\n readonly payload: HostErrorPayload;\n\n constructor(label: string, payload: HostErrorPayload) {\n super(`${label}: ${formatHostError(payload)}`, { cause: payload });\n this.name = \"HostCallFailedError\";\n this.payload = payload;\n }\n}\n\n/** Check whether a value is any {@link HostError}. */\nexport function isHostError(error: unknown): error is HostError {\n return error instanceof HostError;\n}\n\nif (import.meta.vitest) {\n const { test, expect, describe } = import.meta.vitest;\n\n describe(\"host error classes\", () => {\n test(\"HostError is the base class\", () => {\n const e = new HostUnavailableError();\n expect(e).toBeInstanceOf(HostError);\n expect(e).toBeInstanceOf(Error);\n });\n\n test(\"HostUnavailableError default message\", () => {\n const e = new HostUnavailableError();\n expect(e.name).toBe(\"HostUnavailableError\");\n expect(e.message).toBe(\"Host API is not available\");\n });\n\n test(\"HostUnavailableError custom message\", () => {\n expect(new HostUnavailableError(\"nope\").message).toBe(\"nope\");\n });\n\n test(\"HostCallFailedError renders payload and preserves it\", () => {\n const payload: HostErrorPayload = {\n tag: \"Domain\",\n value: {\n tag: \"V1\",\n value: { tag: \"PermissionDenied\", value: { reason: \"user said no\" } },\n },\n };\n const e = new HostCallFailedError(\"requestPermission failed\", payload);\n expect(e).toBeInstanceOf(HostError);\n expect(e.payload).toBe(payload);\n expect(e.cause).toBe(payload);\n expect(e.message).toBe(\"requestPermission failed: PermissionDenied: user said no\");\n });\n\n test(\"HostCallFailedError renders a Domain-wrapped GenericError payload\", () => {\n const e = new HostCallFailedError(\"submit failed\", {\n tag: \"Domain\",\n value: { tag: \"V1\", value: { reason: \"timeout\" } },\n });\n expect(e.message).toBe(\"submit failed: timeout\");\n });\n\n test(\"isHostError narrows host errors only\", () => {\n expect(isHostError(new HostUnavailableError())).toBe(true);\n expect(isHostError(new HostCallFailedError(\"x\", { tag: \"Denied\" }))).toBe(true);\n expect(isHostError(new Error(\"plain\"))).toBe(false);\n expect(isHostError(\"string\")).toBe(false);\n });\n });\n\n describe(\"formatHostError\", () => {\n test(\"renders the TruAPI error payload shapes\", () => {\n // GenericError: { reason }\n expect(formatHostError({ reason: \"boom\" })).toBe(\"boom\");\n // Tagged variant carrying a reason: { tag, value: { reason } }\n expect(formatHostError({ tag: \"Unknown\", value: { reason: \"boom\" } })).toBe(\n \"Unknown: boom\",\n );\n // Unit tagged variant: { tag }\n expect(formatHostError({ tag: \"Full\" })).toBe(\"Full\");\n });\n\n test(\"unwraps the CallError Domain envelope to the domain error\", () => {\n // { tag: \"Domain\", value: { tag: \"V1\", value: <domain error> } }\n expect(\n formatHostError({\n tag: \"Domain\",\n value: { tag: \"V1\", value: { tag: \"PermissionDenied\" } },\n }),\n ).toBe(\"PermissionDenied\");\n expect(\n formatHostError({ tag: \"Domain\", value: { tag: \"V1\", value: { reason: \"boom\" } } }),\n ).toBe(\"boom\");\n // Transport-level CallError variants render as-is.\n expect(formatHostError({ tag: \"Denied\" })).toBe(\"Denied\");\n expect(formatHostError({ tag: \"HostFailure\", value: { reason: \"crashed\" } })).toBe(\n \"HostFailure: crashed\",\n );\n });\n\n test(\"falls back for non-host-error input\", () => {\n expect(formatHostError(new Error(\"plain\"))).toBe(\"plain\");\n expect(formatHostError(\"string err\")).toBe(\"string err\");\n expect(formatHostError({ message: \"loose\" })).toBe(\"loose\");\n });\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Host-routed PAPI `JsonRpcProvider`, backed by `truApi.chain.*`.\n *\n * This is a backport of `@novasamatech/host-api-wrapper`'s\n * `createPapiProvider` (`dist/papiProvider.js`) into product-sdk, with the\n * call layer swapped from the novasama `hostApi` to the\n * `@parity/truapi` client. The JSON-RPC ↔ chainHead bridge handles request\n * dispatch, `chainHead_v1_followEvent` notification synthesis, and operation /\n * broadcast bookkeeping over the structured `truApi.chain.*` methods.\n *\n * **Why a bridge at all.** PAPI speaks the JSON-RPC `chainHead`/`chainSpec`/\n * `transaction` API; the host exposes the same operations as structured,\n * SCALE-typed calls. This module parses each inbound JSON-RPC message, routes it\n * to the matching `truApi.chain` method, and translates the typed follow stream\n * back into JSON-RPC notifications.\n *\n * **Divergences from the upstream:**\n * - No `getSyncProvider` wrapper / no-op fallback provider. The upstream had to\n * defer its async readiness check because `createPapiProvider` was synchronous;\n * here {@link module:container.getHostProvider} is async and runs the\n * `system.featureSupported` gate (throwing `ChainNotSupportedError`) *before*\n * building the provider, so there is no async work left to defer.\n * - `RuntimeSpec.apis` arrives as `Array<{ name, version }>` (truapi) rather than\n * the upstream's `[name, version]` tuples; {@link convertRuntimeToJsonRpc}\n * adjusts the loop accordingly.\n * - The follow stream's transport interrupt (`error`/`complete`) is surfaced as a\n * synthetic `stop` event so the consumer's substrate-client refollows; the\n * upstream's bare callback had no such channel.\n *\n * @module\n */\n\nimport type {\n JsonRpcConnection,\n JsonRpcMessage,\n JsonRpcRequest,\n} from \"@polkadot-api/json-rpc-provider\";\nimport type { JsonRpcProvider } from \"polkadot-api\";\nimport type {\n HexString,\n OperationStartedResult,\n RemoteChainHeadFollowItem,\n RuntimeType,\n StorageQueryType,\n TrUApiClient,\n} from \"@parity/truapi\";\nimport { createLogger } from \"@parity/product-sdk-logger\";\n\nimport { formatHostError } from \"./errors.js\";\nimport { subscribeWithInterrupt, type TransportSubscription } from \"./transport.js\";\n\nconst log = createLogger(\"host:papi\");\n\n/** JSON-RPC internal-error code used for every host-side failure (matches the upstream). */\nconst JSON_RPC_INTERNAL_ERROR = -32603;\n/** JSON-RPC method-not-found code for chainHead methods the host doesn't serve. */\nconst JSON_RPC_METHOD_NOT_FOUND = -32601;\n\n/** A `chainHead_v1_followEvent` payload (loosely typed — consumed by PAPI's substrate-client). */\ntype FollowEvent = { event: string } & Record<string, unknown>;\n\n/** Map a JSON-RPC storage query-type string to the truapi `StorageQueryType` tag. */\nconst STORAGE_TYPE_MAP: Record<string, StorageQueryType> = {\n value: \"Value\",\n hash: \"Hash\",\n closestDescendantMerkleValue: \"ClosestDescendantMerkleValue\",\n descendantsValues: \"DescendantsValues\",\n descendantsHashes: \"DescendantsHashes\",\n};\n\n/**\n * Convert a truapi `RuntimeType` into the JSON-RPC `chainHead` runtime shape.\n * Returns `null` for absent/unknown runtimes. Note `RuntimeSpec.apis` is an\n * array of `{ name, version }` (truapi), flattened here into a `{ name: version }`\n * map as the JSON-RPC spec expects.\n */\nfunction convertRuntimeToJsonRpc(runtime: RuntimeType | undefined): unknown {\n if (!runtime || typeof runtime !== \"object\") return null;\n if (runtime.tag === \"Valid\") {\n const spec = runtime.value;\n const apis: Record<string, number> = {};\n for (const api of spec.apis) {\n apis[api.name] = api.version;\n }\n return {\n type: \"valid\",\n spec: {\n specName: spec.specName,\n implName: spec.implName,\n specVersion: spec.specVersion,\n implVersion: spec.implVersion,\n transactionVersion: spec.transactionVersion,\n apis,\n },\n };\n }\n if (runtime.tag === \"Invalid\") {\n return { type: \"invalid\", error: runtime.value.error };\n }\n return null;\n}\n\n/** Translate a typed follow-stream item into its JSON-RPC `followEvent` form. */\nfunction convertFollowEventToJsonRpc(item: RemoteChainHeadFollowItem): FollowEvent {\n switch (item.tag) {\n case \"Initialized\":\n return {\n event: \"initialized\",\n finalizedBlockHashes: item.value.finalizedBlockHashes,\n finalizedBlockRuntime: convertRuntimeToJsonRpc(item.value.finalizedBlockRuntime),\n };\n case \"NewBlock\":\n return {\n event: \"newBlock\",\n blockHash: item.value.blockHash,\n parentBlockHash: item.value.parentBlockHash,\n newRuntime: convertRuntimeToJsonRpc(item.value.newRuntime),\n };\n case \"BestBlockChanged\":\n return { event: \"bestBlockChanged\", bestBlockHash: item.value.bestBlockHash };\n case \"Finalized\":\n return {\n event: \"finalized\",\n finalizedBlockHashes: item.value.finalizedBlockHashes,\n prunedBlockHashes: item.value.prunedBlockHashes,\n };\n case \"OperationBodyDone\":\n return {\n event: \"operationBodyDone\",\n operationId: item.value.operationId,\n value: item.value.value,\n };\n case \"OperationCallDone\":\n return {\n event: \"operationCallDone\",\n operationId: item.value.operationId,\n output: item.value.output,\n };\n case \"OperationStorageItems\":\n return {\n event: \"operationStorageItems\",\n operationId: item.value.operationId,\n items: item.value.items,\n };\n case \"OperationStorageDone\":\n return { event: \"operationStorageDone\", operationId: item.value.operationId };\n case \"OperationWaitingForContinue\":\n return { event: \"operationWaitingForContinue\", operationId: item.value.operationId };\n case \"OperationInaccessible\":\n return { event: \"operationInaccessible\", operationId: item.value.operationId };\n case \"OperationError\":\n return {\n event: \"operationError\",\n operationId: item.value.operationId,\n error: item.value.error,\n };\n case \"Stop\":\n return { event: \"stop\" };\n default: {\n // Exhaustiveness: a new follow-item tag in @parity/truapi fails to compile here.\n const _exhaustive: never = item;\n return { event: \"stop\" };\n }\n }\n}\n\n/** Map a JSON-RPC storage query-type string to the truapi `StorageQueryType` tag. */\nfunction convertStorageType(type: string): StorageQueryType {\n return STORAGE_TYPE_MAP[type] ?? \"Value\";\n}\n\n/** Translate a truapi `OperationStartedResult` into the JSON-RPC operation-start shape. */\nfunction convertOperationResultToJsonRpc(result: OperationStartedResult): unknown {\n if (result.tag === \"Started\") {\n return { result: \"started\", operationId: result.value.operationId };\n }\n return { result: \"limitReached\" };\n}\n\n/**\n * Build a host-routed PAPI `JsonRpcProvider` for `genesisHash` over the given\n * TruAPI client. The caller is responsible for confirming the host supports the\n * chain (and for the handshake) before calling this — see\n * {@link module:container.getHostProvider}.\n */\nexport function createHostPapiProvider(\n client: TrUApiClient,\n genesisHash: HexString,\n): JsonRpcProvider {\n const chain = client.chain;\n\n return (onMessage: (message: JsonRpcMessage) => void): JsonRpcConnection => {\n const activeFollows = new Map<string, TransportSubscription>();\n const activeBroadcasts = new Set<string>();\n\n function sendJsonRpcResponse(id: JsonRpcRequest[\"id\"], result: unknown): void {\n onMessage({ jsonrpc: \"2.0\", id, result } as JsonRpcMessage);\n }\n function sendJsonRpcError(id: JsonRpcRequest[\"id\"], code: number, message: string): void {\n onMessage({ jsonrpc: \"2.0\", id, error: { code, message } } as JsonRpcMessage);\n }\n function sendFollowEvent(subscription: string, event: FollowEvent): void {\n onMessage({\n jsonrpc: \"2.0\",\n method: \"chainHead_v1_followEvent\",\n params: { subscription, result: event },\n } as JsonRpcMessage);\n }\n\n /** Reject an inbound request with the host's error reason as the JSON-RPC message. */\n const hostError = (id: JsonRpcRequest[\"id\"]) => (error: unknown) =>\n sendJsonRpcError(id, JSON_RPC_INTERNAL_ERROR, formatHostError(error));\n\n function handleMessage(message: JsonRpcRequest): void {\n const { id, method } = message;\n // chainHead/chainSpec/transaction JSON-RPC params are positional arrays.\n const params = (message.params ?? []) as unknown[];\n\n switch (method) {\n case \"chainHead_v1_follow\": {\n const [withRuntime] = params as [boolean];\n // The Stop branch unsubscribes its own host subscription, but the\n // handle is this call's return value — the ref breaks that\n // chicken-and-egg. (Releasing before forwarding the Stop is just\n // cleanup; the consumer's synchronous refollow gets a fresh wire\n // subscription either way.)\n const ref: { handle?: TransportSubscription } = {};\n const pendingItems: RemoteChainHeadFollowItem[] = [];\n const forwardItem = (\n followSubscriptionId: string,\n item: RemoteChainHeadFollowItem,\n ) => {\n if (item.tag === \"Stop\" && activeFollows.delete(followSubscriptionId)) {\n ref.handle?.unsubscribe();\n }\n sendFollowEvent(followSubscriptionId, convertFollowEventToJsonRpc(item));\n };\n ref.handle = subscribeWithInterrupt(\n chain.followHeadSubscribe({ request: { genesisHash, withRuntime } }),\n (item) => {\n const followSubscriptionId = ref.handle?.subscriptionId;\n if (!followSubscriptionId) {\n pendingItems.push(item);\n return;\n }\n forwardItem(followSubscriptionId, item);\n },\n );\n const followSubscriptionId = ref.handle.subscriptionId;\n if (!followSubscriptionId) {\n ref.handle.unsubscribe();\n sendJsonRpcError(\n id,\n JSON_RPC_INTERNAL_ERROR,\n \"Host follow subscription did not start\",\n );\n break;\n }\n // A transport interrupt/close ends the stream without a Stop\n // item; synthesize one so the consumer refollows.\n ref.handle.onInterrupt(() => {\n if (activeFollows.delete(followSubscriptionId)) {\n sendFollowEvent(followSubscriptionId, { event: \"stop\" });\n }\n });\n activeFollows.set(followSubscriptionId, ref.handle);\n sendJsonRpcResponse(id, followSubscriptionId);\n for (const item of pendingItems) {\n forwardItem(followSubscriptionId, item);\n }\n break;\n }\n case \"chainHead_v1_unfollow\": {\n const [followSubId] = params as [string];\n const follow = activeFollows.get(followSubId);\n if (follow) {\n follow.unsubscribe();\n activeFollows.delete(followSubId);\n }\n sendJsonRpcResponse(id, null);\n break;\n }\n case \"chainHead_v1_header\": {\n const [followSubscriptionId, hash] = params as [string, HexString];\n chain\n .getHeadHeader({ genesisHash, followSubscriptionId, hash })\n .match(\n (response) => sendJsonRpcResponse(id, response.header ?? null),\n hostError(id),\n );\n break;\n }\n case \"chainHead_v1_body\": {\n const [followSubscriptionId, hash] = params as [string, HexString];\n chain\n .getHeadBody({ genesisHash, followSubscriptionId, hash })\n .match(\n (response) =>\n sendJsonRpcResponse(\n id,\n convertOperationResultToJsonRpc(response.operation),\n ),\n hostError(id),\n );\n break;\n }\n case \"chainHead_v1_storage\": {\n const [followSubscriptionId, hash, items, childTrie] = params as [\n string,\n HexString,\n Array<{ key: HexString; type: string }>,\n HexString | undefined,\n ];\n const queryItems = items.map((item) => ({\n key: item.key,\n queryType: convertStorageType(item.type),\n }));\n chain\n .getHeadStorage({\n genesisHash,\n followSubscriptionId,\n hash,\n items: queryItems,\n // PAPI passes `null` for an absent child trie, but the\n // truapi codec encodes the optional `childTrie` field as\n // `Option<Hex>` — it treats `undefined` as None yet runs\n // the inner Hex codec on `null`, which throws\n // (`null.startsWith`). Coerce `null` → `undefined`.\n childTrie: childTrie ?? undefined,\n })\n .match(\n (response) =>\n sendJsonRpcResponse(\n id,\n convertOperationResultToJsonRpc(response.operation),\n ),\n hostError(id),\n );\n break;\n }\n case \"chainHead_v1_call\": {\n const [followSubscriptionId, hash, fn, callParameters] = params as [\n string,\n HexString,\n string,\n HexString,\n ];\n chain\n .callHead({\n genesisHash,\n followSubscriptionId,\n hash,\n function: fn,\n callParameters,\n })\n .match(\n (response) =>\n sendJsonRpcResponse(\n id,\n convertOperationResultToJsonRpc(response.operation),\n ),\n hostError(id),\n );\n break;\n }\n case \"chainHead_v1_unpin\": {\n const [followSubscriptionId, hashOrHashes] = params as [\n string,\n HexString | HexString[],\n ];\n const hashes = Array.isArray(hashOrHashes) ? hashOrHashes : [hashOrHashes];\n chain\n .unpinHead({ genesisHash, followSubscriptionId, hashes })\n .match(() => sendJsonRpcResponse(id, null), hostError(id));\n break;\n }\n case \"chainHead_v1_continue\": {\n const [followSubscriptionId, operationId] = params as [string, string];\n chain\n .continueHead({ genesisHash, followSubscriptionId, operationId })\n .match(() => sendJsonRpcResponse(id, null), hostError(id));\n break;\n }\n case \"chainHead_v1_stopOperation\": {\n const [followSubscriptionId, operationId] = params as [string, string];\n chain\n .stopHeadOperation({ genesisHash, followSubscriptionId, operationId })\n .match(() => sendJsonRpcResponse(id, null), hostError(id));\n break;\n }\n case \"chainSpec_v1_genesisHash\": {\n chain\n .getSpecGenesisHash({ genesisHash })\n .match(\n (response) => sendJsonRpcResponse(id, response.genesisHash),\n hostError(id),\n );\n break;\n }\n case \"chainSpec_v1_chainName\": {\n chain\n .getSpecChainName({ genesisHash })\n .match(\n (response) => sendJsonRpcResponse(id, response.chainName),\n hostError(id),\n );\n break;\n }\n case \"chainSpec_v1_properties\": {\n chain.getSpecProperties({ genesisHash }).match((response) => {\n try {\n sendJsonRpcResponse(id, JSON.parse(response.properties));\n } catch {\n sendJsonRpcResponse(id, response.properties);\n }\n }, hostError(id));\n break;\n }\n case \"transaction_v1_broadcast\": {\n const [transaction] = params as [HexString];\n chain.broadcastTransaction({ genesisHash, transaction }).match((response) => {\n const operationId = response.operationId ?? null;\n if (operationId !== null) activeBroadcasts.add(operationId);\n sendJsonRpcResponse(id, operationId);\n }, hostError(id));\n break;\n }\n case \"transaction_v1_stop\": {\n const [operationId] = params as [string];\n activeBroadcasts.delete(operationId);\n chain\n .stopTransaction({ genesisHash, operationId })\n .match(() => sendJsonRpcResponse(id, null), hostError(id));\n break;\n }\n default:\n sendJsonRpcError(\n id,\n JSON_RPC_METHOD_NOT_FOUND,\n `Method \"${method}\" is not supported by the host`,\n );\n break;\n }\n }\n\n return {\n send(message) {\n // A synchronous throw inside a handler (e.g. a malformed positional\n // param) must not leave the JSON-RPC request unsettled — the caller\n // would hang. Surface it as an error response for the request id.\n try {\n handleMessage(message);\n } catch (error) {\n // Handlers must settle the request themselves; reaching here means a\n // synchronous throw before any response was sent. (A handler that\n // sends then throws would double-respond — none do today.)\n log.warn(\"send: handler threw before settling the request\", {\n error: formatHostError(error),\n });\n sendJsonRpcError(message.id, JSON_RPC_INTERNAL_ERROR, formatHostError(error));\n }\n },\n disconnect() {\n for (const handle of activeFollows.values()) {\n handle.unsubscribe();\n }\n activeFollows.clear();\n for (const operationId of activeBroadcasts) {\n // Fire-and-forget: the transport may already be torn down.\n chain.stopTransaction({ genesisHash, operationId }).match(\n () => {},\n () => {},\n );\n }\n activeBroadcasts.clear();\n },\n };\n };\n}\n\nif (import.meta.vitest) {\n const { test, expect, vi } = import.meta.vitest;\n\n // A minimal fake of the truapi chain domain. ResultAsync is approximated by a\n // `.match(ok, err)` thenable; the follow subscription is a hand-driven\n // ObservableLike whose observer we capture to push items at will.\n function makeFakeClient(opts: {\n onCall?: (method: string, args: unknown) => void;\n responses?: Record<string, unknown>;\n /** Methods named here resolve to their `.match` error arm carrying the given value. */\n errors?: Record<string, unknown>;\n /** Unsubscribe spy used by the follow subscription (defaults to a fresh `vi.fn()`). */\n unsubscribe?: () => void;\n /** Item emitted synchronously while the transport subscription starts. */\n initialItem?: unknown;\n captureObserver?: (observer: {\n next: (i: unknown) => void;\n error: (e: unknown) => void;\n complete: () => void;\n }) => void;\n /** Transport request id assigned to the follow subscription. */\n subscriptionId?: string;\n }) {\n const okMatch = (value: unknown) => ({\n match: (ok: (v: unknown) => unknown, _err: (e: unknown) => unknown) => ok(value),\n });\n const errMatch = (error: unknown) => ({\n match: (_ok: (v: unknown) => unknown, err: (e: unknown) => unknown) => err(error),\n });\n const method = (name: string, response: unknown) => (args: unknown) => {\n opts.onCall?.(name, args);\n const errors = opts.errors ?? {};\n return name in errors ? errMatch(errors[name]) : okMatch(response);\n };\n return {\n chain: {\n followHeadSubscribe: (_args: unknown) => ({\n subscribe: (observer: {\n next: (i: unknown) => void;\n error: (e: unknown) => void;\n complete: () => void;\n }) => {\n opts.captureObserver?.(observer);\n if (opts.initialItem !== undefined) {\n observer.next(opts.initialItem);\n }\n return {\n subscriptionId: opts.subscriptionId ?? \"p:41\",\n unsubscribe: opts.unsubscribe ?? vi.fn(),\n };\n },\n [Symbol.observable as symbol]() {\n return this;\n },\n }),\n getHeadHeader: method(\n \"getHeadHeader\",\n opts.responses?.getHeadHeader ?? { header: \"0x01\" },\n ),\n getHeadBody: method(\"getHeadBody\", {\n operation: { tag: \"Started\", value: { operationId: \"op1\" } },\n }),\n getHeadStorage: method(\"getHeadStorage\", { operation: { tag: \"LimitReached\" } }),\n callHead: method(\"callHead\", {\n operation: { tag: \"Started\", value: { operationId: \"op2\" } },\n }),\n unpinHead: method(\"unpinHead\", undefined),\n continueHead: method(\"continueHead\", undefined),\n stopHeadOperation: method(\"stopHeadOperation\", undefined),\n getSpecGenesisHash: method(\"getSpecGenesisHash\", { genesisHash: \"0xabc\" }),\n getSpecChainName: method(\"getSpecChainName\", { chainName: \"Polkadot\" }),\n getSpecProperties: method(\"getSpecProperties\", { properties: '{\"ss58Format\":0}' }),\n broadcastTransaction: method(\"broadcastTransaction\", { operationId: \"bc1\" }),\n stopTransaction: method(\"stopTransaction\", undefined),\n },\n } as unknown as TrUApiClient;\n }\n\n test(\"follow preserves the transport id for events and follow-up requests\", () => {\n let observer:\n | { next: (i: unknown) => void; error: (e: unknown) => void; complete: () => void }\n | undefined;\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({\n subscriptionId: \"p:17\",\n onCall: (method, args) => calls.push([method, args]),\n captureObserver: (o) => {\n observer = o;\n },\n });\n const provider = createHostPapiProvider(client, \"0xfeed\");\n\n const messages: JsonRpcMessage[] = [];\n const conn = provider((m) => messages.push(m));\n\n conn.send({ jsonrpc: \"2.0\", id: 1, method: \"chainHead_v1_follow\", params: [true] });\n expect(messages[0]).toEqual({ jsonrpc: \"2.0\", id: 1, result: \"p:17\" });\n\n // A typed BestBlockChanged item becomes a chainHead_v1_followEvent.\n observer?.next({ tag: \"BestBlockChanged\", value: { bestBlockHash: \"0xbeef\" } });\n expect(messages[1]).toEqual({\n jsonrpc: \"2.0\",\n method: \"chainHead_v1_followEvent\",\n params: {\n subscription: \"p:17\",\n result: { event: \"bestBlockChanged\", bestBlockHash: \"0xbeef\" },\n },\n });\n\n conn.send({\n jsonrpc: \"2.0\",\n id: 2,\n method: \"chainHead_v1_header\",\n params: [\"p:17\", \"0xbeef\"],\n });\n expect(calls).toContainEqual([\n \"getHeadHeader\",\n {\n genesisHash: \"0xfeed\",\n followSubscriptionId: \"p:17\",\n hash: \"0xbeef\",\n },\n ]);\n });\n\n test(\"follow buffers an item emitted while the transport subscription starts\", () => {\n const client = makeFakeClient({\n subscriptionId: \"p:18\",\n initialItem: { tag: \"BestBlockChanged\", value: { bestBlockHash: \"0xbeef\" } },\n });\n const messages: JsonRpcMessage[] = [];\n const conn = createHostPapiProvider(client, \"0xfeed\")((message) => messages.push(message));\n\n conn.send({ jsonrpc: \"2.0\", id: 1, method: \"chainHead_v1_follow\", params: [true] });\n\n expect(messages).toEqual([\n { jsonrpc: \"2.0\", id: 1, result: \"p:18\" },\n {\n jsonrpc: \"2.0\",\n method: \"chainHead_v1_followEvent\",\n params: {\n subscription: \"p:18\",\n result: { event: \"bestBlockChanged\", bestBlockHash: \"0xbeef\" },\n },\n },\n ]);\n });\n\n test(\"chainSpec_v1_properties parses the JSON-encoded properties string\", () => {\n const client = makeFakeClient({});\n const provider = createHostPapiProvider(client, \"0xfeed\");\n const messages: JsonRpcMessage[] = [];\n provider((m) => messages.push(m)).send({\n jsonrpc: \"2.0\",\n id: 7,\n method: \"chainSpec_v1_properties\",\n params: [],\n });\n expect(messages[0]).toEqual({ jsonrpc: \"2.0\", id: 7, result: { ss58Format: 0 } });\n });\n\n test(\"chainHead_v1_body unwraps the operation into a JSON-RPC start result\", () => {\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = createHostPapiProvider(client, \"0xfeed\");\n const messages: JsonRpcMessage[] = [];\n provider((m) => messages.push(m)).send({\n jsonrpc: \"2.0\",\n id: 3,\n method: \"chainHead_v1_body\",\n params: [\"follow_0\", \"0xhash\"],\n });\n expect(calls[0]).toEqual([\n \"getHeadBody\",\n { genesisHash: \"0xfeed\", followSubscriptionId: \"follow_0\", hash: \"0xhash\" },\n ]);\n expect(messages[0]).toEqual({\n jsonrpc: \"2.0\",\n id: 3,\n result: { result: \"started\", operationId: \"op1\" },\n });\n });\n\n test(\"unknown methods produce a method-not-found error\", () => {\n const client = makeFakeClient({});\n const provider = createHostPapiProvider(client, \"0xfeed\");\n const messages: JsonRpcMessage[] = [];\n provider((m) => messages.push(m)).send({\n jsonrpc: \"2.0\",\n id: 9,\n method: \"system_health\",\n params: [],\n });\n expect(messages[0]).toMatchObject({ id: 9, error: { code: -32601 } });\n });\n\n test(\"a transport interrupt synthesizes a stop follow-event\", () => {\n let observer:\n | { next: (i: unknown) => void; error: (e: unknown) => void; complete: () => void }\n | undefined;\n const client = makeFakeClient({\n captureObserver: (o) => {\n observer = o;\n },\n });\n const provider = createHostPapiProvider(client, \"0xfeed\");\n const messages: JsonRpcMessage[] = [];\n const conn = provider((m) => messages.push(m));\n\n conn.send({ jsonrpc: \"2.0\", id: 1, method: \"chainHead_v1_follow\", params: [true] });\n // The stream ends via transport close (no Stop item) — the consumer must\n // still see a stop so its substrate-client refollows.\n observer?.complete();\n expect(messages[1]).toEqual({\n jsonrpc: \"2.0\",\n method: \"chainHead_v1_followEvent\",\n params: { subscription: \"p:41\", result: { event: \"stop\" } },\n });\n });\n\n test(\"a host error becomes a JSON-RPC -32603 with the formatted reason\", () => {\n const client = makeFakeClient({ errors: { getHeadHeader: { reason: \"no such block\" } } });\n const provider = createHostPapiProvider(client, \"0xfeed\");\n const messages: JsonRpcMessage[] = [];\n provider((m) => messages.push(m)).send({\n jsonrpc: \"2.0\",\n id: 4,\n method: \"chainHead_v1_header\",\n params: [\"follow_0\", \"0xhash\"],\n });\n expect(messages[0]).toEqual({\n jsonrpc: \"2.0\",\n id: 4,\n error: { code: -32603, message: \"no such block\" },\n });\n });\n\n test(\"disconnect unsubscribes active follows and stops active broadcasts\", () => {\n const unsubscribe = vi.fn();\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ unsubscribe, onCall: (m, a) => calls.push([m, a]) });\n const provider = createHostPapiProvider(client, \"0xfeed\");\n const conn = provider(() => {});\n\n // Open a follow and an in-flight broadcast (operationId \"bc1\" is tracked).\n conn.send({ jsonrpc: \"2.0\", id: 1, method: \"chainHead_v1_follow\", params: [true] });\n conn.send({ jsonrpc: \"2.0\", id: 2, method: \"transaction_v1_broadcast\", params: [\"0xtx\"] });\n\n conn.disconnect();\n\n // The follow subscription is torn down...\n expect(unsubscribe).toHaveBeenCalledTimes(1);\n // ...and the tracked broadcast is stopped on the way out.\n expect(calls).toContainEqual([\n \"stopTransaction\",\n { genesisHash: \"0xfeed\", operationId: \"bc1\" },\n ]);\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * TruAPI - the protocol for communicating between apps and the Polkadot host container.\n *\n * This module centralizes access to the in-house `@parity/truapi` client,\n * allowing other `@parity/product-sdk-*` packages to import from here rather\n * than depending directly on the protocol package. The client is built and\n * cached by {@link module:transport}; this module adds the accessor plus the\n * two helpers the convenience wrappers fold truapi's `ResultAsync` through —\n * {@link mapHostResult} (returns a `Result`, used by the public operations) and\n * {@link unwrapHostResult} (throws, used by the adapter-object methods).\n *\n * @module\n */\n\nimport { scale } from \"@parity/truapi\";\nimport type {\n AllocatableResource,\n AllocationOutcome,\n HexString,\n RemotePermission,\n TrUApiClient,\n} from \"@parity/truapi\";\nimport { createLogger } from \"@parity/product-sdk-logger\";\n\nimport {\n type HostError,\n type HostErrorPayload,\n HostCallFailedError,\n HostUnavailableError,\n formatHostError,\n} from \"./errors.js\";\nimport { type Result, err, ok } from \"./result.js\";\nimport { getClient, subscribeWithInterrupt } from \"./transport.js\";\nimport type { HostSubscription, Statement, StatementProof } from \"./types.js\";\n\nconst log = createLogger(\"host\");\n\n/**\n * Await a host `ResultAsync`, returning its Ok value or throwing a diagnostic\n * `Error` built from the host's error payload (preserved as `cause`).\n *\n * This is the *throwing* helper, retained for the methods of the adapter objects\n * returned by the feature-detection getters (`PreimageManager.submit`,\n * `HostLocalStorage.read`, `AccountsProvider` signing, …). Those objects often\n * implement external interfaces (e.g. polkadot-api's `JsonRpcProvider`) whose\n * method signatures can't carry a {@link Result}, so they keep the\n * throw convention. The flat public operations use {@link mapHostResult} instead.\n */\nexport function unwrapHostResult<T, E>(result: ResultAsync<T, E>, label: string): Promise<T> {\n return result.match(\n (value) => value,\n (error: E) => {\n throw new Error(`${label}: ${formatHostError(error)}`, { cause: error });\n },\n );\n}\n\n/**\n * Await a host `ResultAsync` and fold it into a tagged {@link Result}: maps the\n * Ok value through `map`, or wraps the host error payload in a\n * {@link HostCallFailedError} on the `err` channel. This is the non-throwing\n * boundary the flat public host operations (`requestPermission`, `deriveEntropy`,\n * `requestResourceAllocation`, …) return through.\n */\nexport function mapHostResult<T, U>(\n result: ResultAsync<T, HostErrorPayload>,\n map: (value: T) => U,\n label: string,\n): Promise<Result<U, HostError>> {\n return result.match(\n (value) => ok(map(value)),\n (error) => err(new HostCallFailedError(label, error)),\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hex helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Convert bytes to a `0x`-prefixed lower-case hex string. */\nexport function toHex(bytes: Uint8Array): HexString {\n return scale.bytesToHex(bytes);\n}\n\n/** Convert a hex string (with or without `0x`) to bytes. */\nexport function fromHex(hex: string): Uint8Array {\n return scale.hexToBytes(hex);\n}\n\n/** A `0x`-prefixed hex string used by the host API surface for raw byte payloads. */\nexport type { HexString };\n\n// ─────────────────────────────────────────────────────────────────────────────\n// TruAPI accessor\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The TruApi client — namespaced access to every host protocol domain\n * (`permissions`, `entropy`, `signing`, `statementStore`, `system`,\n * `localStorage`, …). Identical to `TrUApiClient` from `@parity/truapi`.\n *\n * @example\n * ```ts\n * const truApi = await getTruApi();\n * if (truApi) {\n * await truApi.permissions.requestRemotePermission({\n * permission: { tag: \"ChainSubmit\", value: undefined },\n * });\n * await truApi.system.navigateTo({ url: \"polkadot://settings\" });\n * }\n * ```\n */\nexport type TruApi = TrUApiClient;\n\n/**\n * Get the TruAPI client for direct low-level access to host protocol domains.\n *\n * Returns the cached `@parity/truapi` client once the host transport is built\n * and the handshake has run, or `null` when running outside a container.\n *\n * For most use cases, prefer the higher-level functions like\n * {@link requestPermission}, {@link deriveEntropy}, or `getHostLocalStorage()`.\n *\n * @returns The TruAPI client, or `null` if unavailable.\n */\nexport async function getTruApi(): Promise<TruApi | null> {\n return getClient();\n}\n\n/**\n * Preimage manager handle for bulletin chain operations, backed by\n * `truApi.preimage.*`. `lookup` opens a {@link HostSubscription} (`unsubscribe`\n * + `onInterrupt`) that delivers the preimage bytes — or `null` until the host\n * finds them; `submit` uploads a preimage and resolves to its `0x`-prefixed hex\n * key.\n */\nexport interface PreimageManager {\n lookup(key: HexString, callback: (preimage: Uint8Array | null) => void): HostSubscription;\n submit(value: Uint8Array): Promise<HexString>;\n}\n\n/** Build a {@link PreimageManager} over a TruAPI client's `preimage` domain. */\nfunction adaptPreimageManager(client: TrUApiClient): PreimageManager {\n const preimage = client.preimage;\n return {\n lookup(key, callback) {\n return subscribeWithInterrupt(preimage.lookupSubscribe({ request: { key } }), (item) =>\n callback(item.value !== undefined ? fromHex(item.value) : null),\n );\n },\n submit(value) {\n return unwrapHostResult(preimage.submit(toHex(value)), \"preimage submit failed\");\n },\n };\n}\n\n/**\n * Get the preimage manager for bulletin chain operations.\n *\n * @returns The preimage manager, or `null` if unavailable (outside a container).\n */\nexport async function getPreimageManager(): Promise<PreimageManager | null> {\n const client = await getClient();\n return client ? adaptPreimageManager(client) : null;\n}\n\n/**\n * Construct a `PreimageManager`. Retained for API compatibility; with the single\n * cached TruAPI client this is equivalent to {@link getPreimageManager}.\n *\n * @returns A `PreimageManager` instance, or `null` if unavailable.\n */\nexport async function createHostPreimageManager(): Promise<PreimageManager | null> {\n return getPreimageManager();\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Resource allocation\n// ─────────────────────────────────────────────────────────────────────────────\n\n// Resource-allocation / permission types, re-exported verbatim from\n// `@parity/truapi` (imported above for the local signatures):\n// - `AllocatableResource` — resource types requestable via `requestResourceAllocation`.\n// Its `SmartContractAllowance` variant carries the tagged `DerivationIndex`\n// selector (`{ tag: \"Index\", value: number }` for a plain index, `{ tag:\n// \"Raw\", value: HexString }` for a raw 32-byte index).\n// - `AllocationOutcome` — per-resource outcome, the string union\n// `\"Allocated\" | \"Rejected\" | \"NotAvailable\"` (RFC-10).\n// - `RemotePermission` — permission the dapp asks the host to grant via `requestPermission`.\nexport type { AllocatableResource, AllocationOutcome, RemotePermission };\n\n/**\n * Request the host to pre-allocate one or more resource allowances.\n *\n * The host prompts the user once; subsequent operations covered by the\n * granted allowance don't re-prompt.\n *\n * @param resources - Resources to request.\n * @returns `ok` with per-resource outcomes in the same order as `resources`, or\n * `err(HostUnavailableError | HostCallFailedError)`.\n *\n * @example\n * ```ts\n * const r = await requestResourceAllocation([\n * { tag: \"BulletinAllowance\", value: undefined },\n * ]);\n * if (r.ok && r.value[0] === \"Allocated\") { ... }\n * ```\n */\nexport async function requestResourceAllocation(\n resources: AllocatableResource[],\n): Promise<Result<AllocationOutcome[], HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n return err(new HostUnavailableError(\"requestResourceAllocation: TruAPI unavailable\"));\n }\n log.debug(\"requestResourceAllocation\", { resources: resources.map((r) => r.tag) });\n\n return mapHostResult(\n truApi.resourceAllocation.request({ resources }),\n (response) => response.outcomes,\n \"requestResourceAllocation failed\",\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Authorized Statement Store proof creation (RFC-10 §\"Statement Store allowance\")\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Have the host sign a Statement using the product's allowance-bearing account,\n * which it picks internally — RFC-10 §\"Statement Store allowance\". No per-call\n * account id is needed (this is the sponsored-submission path).\n *\n * Pairs with {@link getStatementStore}'s `submit`: call this to obtain a proof,\n * attach it to the Statement, and submit the result.\n *\n * @param statement - The Statement to be signed.\n * @returns `ok` with the proof to attach before submitting, or\n * `err(HostUnavailableError | HostCallFailedError)`.\n */\nexport async function createProofAuthorized(\n statement: Statement,\n): Promise<Result<StatementProof, HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n return err(new HostUnavailableError(\"createProofAuthorized: TruAPI unavailable\"));\n }\n log.debug(\"createProofAuthorized\", { topics: statement.topics.length });\n\n return mapHostResult(\n truApi.statementStore.createProofAuthorized(statement),\n (response) => response.proof,\n \"createProofAuthorized failed\",\n );\n}\n\n/**\n * Neverthrow-style ResultAsync returned by product-sdk methods.\n *\n * Use `.match(onOk, onErr)` to handle success/error cases.\n */\nexport interface ResultAsync<T, E> {\n match: <A, B = A>(ok: (t: T) => A, err: (e: E) => B) => Promise<A | B>;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Tests\n// ─────────────────────────────────────────────────────────────────────────────\n\nif (import.meta.vitest) {\n const { test, expect } = import.meta.vitest;\n\n test(\"getTruApi returns null outside a container\", async () => {\n const api = await getTruApi();\n expect(api === null || typeof api === \"object\").toBe(true);\n });\n\n test(\"getPreimageManager returns manager or null\", async () => {\n const manager = await getPreimageManager();\n expect(manager === null || typeof manager === \"object\").toBe(true);\n });\n\n test(\"createHostPreimageManager returns null outside container\", async () => {\n expect(await createHostPreimageManager()).toBeNull();\n });\n\n test(\"hex helpers\", () => {\n expect(toHex(new Uint8Array([0xde, 0xad]))).toBe(\"0xdead\");\n expect(Array.from(fromHex(\"0xdead\"))).toEqual([0xde, 0xad]);\n });\n\n test(\"requestResourceAllocation returns err when TruAPI is unavailable\", async () => {\n const api = await getTruApi();\n if (api === null) {\n const result = await requestResourceAllocation([\n { tag: \"BulletinAllowance\", value: undefined },\n ]);\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error).toBeInstanceOf(HostUnavailableError);\n }\n } else {\n expect(typeof requestResourceAllocation).toBe(\"function\");\n }\n });\n\n test(\"createProofAuthorized is callable\", () => {\n expect(typeof createProofAuthorized).toBe(\"function\");\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\nimport type { JsonRpcProvider } from \"polkadot-api\";\nimport type { HexString, TrUApiClient } from \"@parity/truapi\";\n\nimport { formatHostError } from \"./errors.js\";\nimport { createHostPapiProvider } from \"./papi-provider.js\";\nimport { getClient, isCorrectEnvironment, subscribeWithInterrupt } from \"./transport.js\";\nimport { fromHex, toHex, unwrapHostResult } from \"./truapi.js\";\nimport type { HostLocalStorage, HostStatementStore } from \"./types.js\";\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Synchronous container detection — fast heuristic check (iframe, webview\n * marker, or injected host message port). Re-exported from the transport\n * bootstrap, which owns the detection logic.\n */\nexport { isCorrectEnvironment as isInsideContainerSync } from \"./transport.js\";\n\n/**\n * Thrown by {@link getHostProvider} when the host container is reachable but does\n * not support the requested chain — e.g. the chain isn't enabled in this host\n * build, or the descriptor's genesis hash has drifted from the host's after a\n * network reset.\n *\n * Surfacing this as a thrown error (rather than handing back a provider that\n * silently swallows every JSON-RPC request) is what lets callers of\n * `createChainClient` detect the failure. Without it, the host's fallback no-op\n * provider drops every request on the floor and queries await forever.\n */\nexport class ChainNotSupportedError extends Error {\n /** Genesis hash of the chain the host refused, for programmatic detection. */\n readonly genesisHash: string;\n\n constructor(genesisHash: string) {\n super(\n `Chain ${genesisHash} is not supported by the current host. It may not be enabled in this host build, or its genesis hash may have drifted after a network reset.`,\n );\n this.name = \"ChainNotSupportedError\";\n this.genesisHash = genesisHash;\n }\n}\n\n/**\n * Ask the host whether it can serve the given chain, via\n * `system.featureSupported({ tag: \"Chain\", … })`. Gates {@link getHostProvider}\n * the same way the upstream wrapper's provider gated itself internally before\n * deciding whether to start a real provider or a no-op one.\n *\n * @throws If the host rejects the support check outright — a non-hanging,\n * catchable failure.\n */\nasync function isChainSupportedByHost(\n client: TrUApiClient,\n genesisHash: HexString,\n): Promise<boolean> {\n return client.system.featureSupported({ tag: \"Chain\", value: { genesisHash } }).match(\n (response) => response.supported,\n (error) => {\n throw new Error(\n `Host rejected the chain-support check for ${genesisHash}: ${formatHostError(error)}`,\n );\n },\n );\n}\n\n/**\n * Detect if running inside a Host container (Polkadot Browser / Polkadot Desktop).\n *\n * The SDK is designed to run exclusively inside a host container. This function\n * is primarily useful for early validation or informational purposes.\n */\nexport async function isInsideContainer(): Promise<boolean> {\n return isCorrectEnvironment();\n}\n\n/**\n * Adapt the TruAPI client's raw `localStorage` domain (hex-encoded\n * `read`/`write`/`clear`) into the richer {@link HostLocalStorage} surface that\n * the Storage package's `KvStore` and other consumers expect.\n */\nfunction adaptLocalStorage(client: TrUApiClient): HostLocalStorage {\n const ls = client.localStorage;\n\n async function readBytes(key: string): Promise<Uint8Array | undefined> {\n const response = await unwrapHostResult(ls.read({ key }), \"host localStorage read failed\");\n return response.value !== undefined ? fromHex(response.value) : undefined;\n }\n\n async function writeBytes(key: string, value: Uint8Array): Promise<void> {\n await unwrapHostResult(\n ls.write({ key, value: toHex(value) }),\n \"host localStorage write failed\",\n );\n }\n\n async function readString(key: string): Promise<string> {\n const bytes = await readBytes(key);\n return bytes ? textDecoder.decode(bytes) : \"\";\n }\n\n async function writeString(key: string, value: string): Promise<void> {\n return writeBytes(key, textEncoder.encode(value));\n }\n\n async function readJSON(key: string): Promise<unknown> {\n const text = await readString(key);\n return text ? JSON.parse(text) : null;\n }\n\n async function writeJSON(key: string, value: unknown): Promise<void> {\n return writeString(key, JSON.stringify(value));\n }\n\n async function clear(key: string): Promise<void> {\n await unwrapHostResult(ls.clear({ key }), \"host localStorage clear failed\");\n }\n\n return { readString, writeString, readJSON, writeJSON, readBytes, writeBytes, clear };\n}\n\n/**\n * Get the Host API localStorage instance when running inside a container.\n * Returns null outside a container or when the host transport is unavailable.\n */\nexport async function getHostLocalStorage(): Promise<HostLocalStorage | null> {\n const client = await getClient();\n return client ? adaptLocalStorage(client) : null;\n}\n\n/**\n * Construct a host-backed `HostLocalStorage` instance. Retained for API\n * compatibility; with the single cached TruAPI client this is equivalent to\n * {@link getHostLocalStorage}.\n *\n * @returns A `HostLocalStorage` instance, or `null` if unavailable.\n */\nexport async function createHostLocalStorage(): Promise<HostLocalStorage | null> {\n return getHostLocalStorage();\n}\n\n/**\n * Get a PAPI-compatible JSON-RPC provider that routes through the host connection.\n *\n * When running inside a Polkadot container, this builds a `JsonRpcProvider` over\n * `truApi.chain.*` (see {@link module:papi-provider}), enabling shared\n * connections and efficient routing. Returns `null` when not running inside a\n * container.\n *\n * @param genesisHash - Genesis hash of the target chain (`0x`-prefixed hex string).\n * @returns A host-routed `JsonRpcProvider`, or `null` if unavailable.\n * @throws {ChainNotSupportedError} When inside a container but the host can't serve\n * the chain — surfaced instead of returning a provider that would hang forever.\n */\nexport async function getHostProvider(genesisHash: HexString): Promise<JsonRpcProvider | null> {\n const client = await getClient();\n if (!client) return null;\n return resolveHostProvider(client, genesisHash);\n}\n\n/**\n * Decide whether to build a host provider for `genesisHash`, given a ready\n * TruAPI client. Split out of {@link getHostProvider} so the decision logic can\n * be unit-tested with a fake client.\n *\n * @returns the provider.\n * @throws {ChainNotSupportedError} when the host can't serve the chain.\n */\nasync function resolveHostProvider(\n client: TrUApiClient,\n genesisHash: HexString,\n): Promise<JsonRpcProvider> {\n // Confirm the host can actually serve this chain before handing PAPI a\n // provider. When the host doesn't support the chain, a provider would silently\n // swallow every JSON-RPC request and the caller hangs forever with no\n // rejection. Surface a catchable error instead.\n if (!(await isChainSupportedByHost(client, genesisHash))) {\n throw new ChainNotSupportedError(genesisHash);\n }\n\n return createHostPapiProvider(client, genesisHash);\n}\n\n/** Build a {@link HostStatementStore} over a TruAPI client's `statementStore` domain. */\nfunction adaptStatementStore(client: TrUApiClient): HostStatementStore {\n const ss = client.statementStore;\n return {\n subscribe(filter, callback) {\n const request =\n \"matchAll\" in filter\n ? ({ tag: \"MatchAll\", value: filter.matchAll } as const)\n : ({ tag: \"MatchAny\", value: filter.matchAny } as const);\n // `RemoteStatementStoreSubscribeItem` is structurally a StatementsPage.\n return subscribeWithInterrupt(ss.subscribe({ request }), callback);\n },\n async createProofAuthorized(statement) {\n const response = await unwrapHostResult(\n ss.createProofAuthorized(statement),\n \"createProofAuthorized failed\",\n );\n return response.proof;\n },\n async submit(signedStatement) {\n await unwrapHostResult(ss.submit(signedStatement), \"statement submit failed\");\n },\n };\n}\n\n/**\n * Get the host statement store when running inside a container, backed by\n * `truApi.statementStore.*`.\n *\n * Returns a store with `subscribe`, `createProofAuthorized`, and `submit` that\n * communicate through the host's native binary protocol — bypassing JSON-RPC\n * entirely. Returns `null` outside a host container.\n *\n * @returns The host statement store, or `null` if unavailable.\n */\nexport async function getStatementStore(): Promise<HostStatementStore | null> {\n const client = await getClient();\n return client ? adaptStatementStore(client) : null;\n}\n\nif (import.meta.vitest) {\n const { test, expect, vi, afterEach } = import.meta.vitest;\n\n afterEach(() => {\n vi.unstubAllGlobals();\n });\n\n // A self-contained fake TruAPI client exposing just the `system` and `chain`\n // domains the provider gate touches, so the chain-support decision can be\n // tested without a real host connection.\n function makeFakeClient(opts: { supported?: boolean; featureErr?: string | null }) {\n const { supported = true, featureErr = null } = opts;\n return {\n system: {\n featureSupported: (_request: unknown) => ({\n match: (\n okFn: (ok: { supported: boolean }) => boolean,\n errFn: (err: { reason: string }) => boolean,\n ) => (featureErr ? errFn({ reason: featureErr }) : okFn({ supported })),\n }),\n },\n // Read synchronously by createHostPapiProvider; never invoked here.\n chain: {},\n } as unknown as TrUApiClient;\n }\n\n test(\"isInsideContainer is false in a Node environment (no window)\", async () => {\n expect(await isInsideContainer()).toBe(false);\n });\n\n test(\"isInsideContainer detects an injected host port\", async () => {\n const win = {};\n Object.defineProperty(win, \"top\", { get: () => win });\n (win as Record<string, unknown>).__HOST_API_PORT__ = 12345;\n vi.stubGlobal(\"window\", win);\n expect(await isInsideContainer()).toBe(true);\n });\n\n test(\"getHostLocalStorage returns null outside container\", async () => {\n expect(await getHostLocalStorage()).toBeNull();\n });\n\n test(\"createHostLocalStorage returns null outside container\", async () => {\n expect(await createHostLocalStorage()).toBeNull();\n });\n\n test(\"adaptLocalStorage round-trips strings, JSON, and bytes over the TruAPI client\", async () => {\n // Minimal in-memory fake of the TruAPI localStorage domain (hex values).\n const store = new Map<string, `0x${string}`>();\n const okAsync = <T>(value: T) => ({\n match: async (onOk: (v: T) => unknown) => onOk(value),\n });\n const fakeClient = {\n localStorage: {\n read: ({ key }: { key: string }) => okAsync({ value: store.get(key) }),\n write: ({ key, value }: { key: string; value: `0x${string}` }) => {\n store.set(key, value);\n return okAsync(undefined);\n },\n clear: ({ key }: { key: string }) => {\n store.delete(key);\n return okAsync(undefined);\n },\n },\n } as unknown as TrUApiClient;\n\n const ls = adaptLocalStorage(fakeClient);\n expect(await ls.readString(\"missing\")).toBe(\"\");\n expect(await ls.readJSON(\"missing\")).toBeNull();\n expect(await ls.readBytes(\"missing\")).toBeUndefined();\n\n await ls.writeString(\"s\", \"hello\");\n expect(await ls.readString(\"s\")).toBe(\"hello\");\n\n await ls.writeJSON(\"j\", { a: 1 });\n expect(await ls.readJSON(\"j\")).toEqual({ a: 1 });\n\n await ls.writeBytes(\"b\", new Uint8Array([1, 2, 3]));\n expect(Array.from((await ls.readBytes(\"b\")) ?? [])).toEqual([1, 2, 3]);\n\n await ls.clear(\"s\");\n expect(await ls.readString(\"s\")).toBe(\"\");\n });\n\n // --- chain-support gating (resolveHostProvider over truApi.system/chain) ---\n\n test(\"resolves to a provider when the host supports the chain\", async () => {\n const provider = await resolveHostProvider(makeFakeClient({ supported: true }), \"0xabc\");\n // createHostPapiProvider returns a JsonRpcProvider (an onMessage -> connection fn).\n expect(typeof provider).toBe(\"function\");\n });\n\n test(\"throws ChainNotSupportedError when the host doesn't support the chain\", async () => {\n const err = await resolveHostProvider(makeFakeClient({ supported: false }), \"0xfeed\").catch(\n (e) => e,\n );\n expect(err).toBeInstanceOf(ChainNotSupportedError);\n expect((err as ChainNotSupportedError).genesisHash).toBe(\"0xfeed\");\n });\n\n test(\"throws when the host rejects the support check\", async () => {\n await expect(\n resolveHostProvider(makeFakeClient({ featureErr: \"boom\" }), \"0xabc\"),\n ).rejects.toThrow(/boom/);\n });\n\n test(\"getHostProvider returns null outside a container\", async () => {\n expect(await getHostProvider(\"0xabc\")).toBeNull();\n });\n\n test(\"getStatementStore returns null outside a container\", async () => {\n expect(await getStatementStore()).toBeNull();\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Shared chain network configuration — single source of truth for\n * chain-specific endpoints used by multiple packages.\n */\n\n/**\n * Bulletin Chain RPC endpoints per network environment. `paseo` (Paseo Next v2)\n * and `devnet` (public Paseo testnet) are populated today; `polkadot` and\n * `kusama` are reserved for when those Bulletin deployments go live.\n */\nexport const BULLETIN_RPCS = {\n paseo: [\"wss://paseo-bulletin-next-rpc.polkadot.io\"],\n devnet: [\"wss://bulletin-paseo.tservices.es:8443\"],\n polkadot: [] as string[],\n kusama: [] as string[],\n} as const;\n\n/** Default Bulletin Chain endpoint — the first entry under {@link BULLETIN_RPCS}.paseo. */\nexport const DEFAULT_BULLETIN_ENDPOINT: string = BULLETIN_RPCS.paseo[0];\n\nif (import.meta.vitest) {\n const { describe, test, expect } = import.meta.vitest;\n\n describe(\"chains config\", () => {\n test(\"BULLETIN_RPCS has paseo endpoint\", () => {\n expect(BULLETIN_RPCS.paseo.length).toBeGreaterThan(0);\n expect(BULLETIN_RPCS.paseo[0]).toMatch(/^wss:\\/\\//);\n });\n\n test(\"BULLETIN_RPCS has devnet endpoint\", () => {\n expect(BULLETIN_RPCS.devnet.length).toBeGreaterThan(0);\n expect(BULLETIN_RPCS.devnet[0]).toMatch(/^wss:\\/\\//);\n });\n\n test(\"BULLETIN_RPCS polkadot and kusama are empty until live\", () => {\n expect(BULLETIN_RPCS.polkadot).toEqual([]);\n expect(BULLETIN_RPCS.kusama).toEqual([]);\n });\n\n test(\"DEFAULT_BULLETIN_ENDPOINT matches first paseo endpoint\", () => {\n expect(DEFAULT_BULLETIN_ENDPOINT).toBe(BULLETIN_RPCS.paseo[0]);\n });\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Wrapper for calling this product's own background worker from its rendered\n * surface (App, Widget, or Funding).\n *\n * A product ships two things: the web application the host renders, and a\n * single background worker published at `worker.<product_id>.<tld>`. They run\n * in different sandboxes and cannot reach each other directly. This module is\n * the host-mediated path between them.\n *\n * **What crosses is data, never code.** `call(apiName, payload)` names an\n * export the worker archive already declared; the host resolves it against the\n * pinned, verified bundle. A page cannot hand the worker a function, a script,\n * or an import path — that would let anything able to inject into the page\n * (an XSS, a compromised dependency) run with worker authority, which is\n * strictly wider than the page's own.\n *\n * **The page never names the product.** The host supplies the product identity\n * from the surface it is rendering, so this call can only ever reach *your*\n * worker.\n *\n * **Opt in on chain, not here.** The host only routes this call when the worker\n * manifest declares the surface in `includes`. A worker published without it\n * answers `unavailable`, exactly as a host with no worker support would.\n *\n * ```ts\n * const worker = getWorkerManager();\n * const { jobId } = await worker.call<{ jobId: string }>(\"startSettlement\", {\n * rail: \"BANK\",\n * intentId,\n * });\n * ```\n *\n * @module\n */\n\nimport { HostError, HostUnavailableError } from \"./errors.js\";\n\n/**\n * Why a worker call did not produce a result — the frozen error set the host\n * runtime reports, surfaced verbatim so callers can branch rather than parse\n * a message.\n *\n * - `unavailable` — no worker registered, the user disabled it, the manifest\n * declares no ceiling for this surface, or the worker is in crash\n * quarantine. This is the one worth handling: it is the normal answer on a\n * host that does not run workers at all.\n * - `denied` — the call passed the ceiling but failed a downstream\n * authorization check.\n * - `invalid` — the worker exports no such name, or the payload is malformed\n * or over the host's size bound.\n * - `timeout` — the call outlived its deadline and was revoked.\n * - `crashed` — the worker threw or died handling the call.\n * - `version` — the worker and host disagree on the protocol.\n */\nexport type WorkerErrorTag =\n | \"unavailable\"\n | \"denied\"\n | \"invalid\"\n | \"timeout\"\n | \"crashed\"\n | \"version\";\n\n/**\n * A worker call that reached the host and came back without a result. Branch\n * on {@link WorkerCallError.tag}; `unavailable` is the expected answer when the\n * product ships no worker or the user has switched it off, so treat it as a\n * capability check rather than a fault.\n */\nexport class WorkerCallError extends HostError {\n /** Which of the frozen failure modes this was. */\n readonly tag: WorkerErrorTag;\n\n constructor(tag: WorkerErrorTag, reason?: string) {\n super(reason ? `worker call failed: ${tag} (${reason})` : `worker call failed: ${tag}`);\n this.name = \"WorkerCallError\";\n this.tag = tag;\n }\n}\n\n/**\n * Handle for this product's background worker. Obtain one with\n * {@link getWorkerManager}.\n */\nexport interface WorkerManager {\n /**\n * Whether the host exposes the worker bridge at all. `false` outside a host\n * container, and on hosts that predate the bridge. A `true` here does not\n * promise the product *has* a worker — that surfaces as an `unavailable`\n * {@link WorkerCallError} on the first call.\n */\n isAvailable(): boolean;\n\n /**\n * Invoke an export the worker archive declared.\n *\n * @param apiName - Export name, as published in the worker bundle.\n * @param payload - JSON-serialisable arguments. Bounded by the host's\n * payload ceiling; keep it to identifiers and parameters, not blobs.\n * @param options - `deadlineMs` overrides the host default and is clamped\n * to the host's own window.\n * @throws {@link WorkerCallError} for every typed failure, and\n * {@link HostUnavailableError} when there is no host bridge at all.\n */\n call<Result = unknown>(\n apiName: string,\n payload?: unknown,\n options?: { deadlineMs?: number },\n ): Promise<Result>;\n}\n\n/**\n * The bridge the host installs on the page, mirroring the shape already used\n * by the Pocket capability bridge so one transport serves both.\n */\ntype WorkerBridge = (apiName: string, payloadJson: string, deadlineMs?: number) => Promise<string>;\n\nconst ERROR_TAGS: readonly WorkerErrorTag[] = [\n \"unavailable\",\n \"denied\",\n \"invalid\",\n \"timeout\",\n \"crashed\",\n \"version\",\n];\n\nfunction readBridge(): WorkerBridge | null {\n const host = (globalThis as { __polkadotHost?: { workerCall?: unknown } }).__polkadotHost;\n const bridge = host?.workerCall;\n return typeof bridge === \"function\" ? (bridge as WorkerBridge) : null;\n}\n\nfunction isErrorTag(value: unknown): value is WorkerErrorTag {\n return typeof value === \"string\" && (ERROR_TAGS as readonly string[]).includes(value);\n}\n\n/**\n * Turn the bridge's JSON answer into a result or a typed error.\n *\n * An unrecognised `error` value is reported as `unavailable` rather than\n * thrown away: a host that grows a new failure mode should degrade the same\n * way as a host with no worker support, not crash the page.\n */\nfunction parseAnswer<Result>(raw: string): Result {\n let answer: unknown;\n try {\n answer = JSON.parse(raw);\n } catch {\n throw new WorkerCallError(\"invalid\", \"host answer was not JSON\");\n }\n if (answer && typeof answer === \"object\" && \"error\" in answer) {\n const { error, reason } = answer as { error: unknown; reason?: unknown };\n throw new WorkerCallError(\n isErrorTag(error) ? error : \"unavailable\",\n typeof reason === \"string\" ? reason : undefined,\n );\n }\n return answer as Result;\n}\n\n/**\n * Get the handle for this product's background worker.\n *\n * Follows the singleton accessor pattern used by `getNotificationManager` and\n * `getPaymentManager`: cheap to call repeatedly, no setup, resolves the bridge\n * lazily so a page that never talks to its worker pays nothing.\n */\nexport function getWorkerManager(): WorkerManager {\n return {\n isAvailable() {\n return readBridge() !== null;\n },\n async call<Result = unknown>(\n apiName: string,\n payload?: unknown,\n options?: { deadlineMs?: number },\n ): Promise<Result> {\n const bridge = readBridge();\n if (!bridge) {\n throw new HostUnavailableError(\"no host worker bridge on this page\");\n }\n const raw = await bridge(apiName, JSON.stringify(payload ?? {}), options?.deadlineMs);\n return parseAnswer<Result>(raw);\n },\n };\n}\n\nif (import.meta.vitest) {\n const { test, expect, afterEach } = import.meta.vitest;\n\n type Bridged = typeof globalThis & { __polkadotHost?: { workerCall?: unknown } };\n\n const install = (workerCall: unknown) => {\n (globalThis as Bridged).__polkadotHost = { workerCall };\n };\n\n afterEach(() => {\n (globalThis as Bridged).__polkadotHost = undefined;\n });\n\n test(\"reports unavailable when the host installs no bridge\", () => {\n expect(getWorkerManager().isAvailable()).toBe(false);\n });\n\n test(\"calling without a bridge throws HostUnavailableError\", async () => {\n await expect(getWorkerManager().call(\"startSettlement\")).rejects.toBeInstanceOf(\n HostUnavailableError,\n );\n });\n\n test(\"passes the api name and a JSON payload to the bridge\", async () => {\n const seen: unknown[] = [];\n install((apiName: string, payloadJson: string, deadlineMs?: number) => {\n seen.push([apiName, payloadJson, deadlineMs]);\n return Promise.resolve('{\"jobId\":\"j-1\"}');\n });\n const result = await getWorkerManager().call<{ jobId: string }>(\n \"startSettlement\",\n { rail: \"BANK\" },\n { deadlineMs: 5_000 },\n );\n expect(result).toEqual({ jobId: \"j-1\" });\n expect(seen).toEqual([[\"startSettlement\", '{\"rail\":\"BANK\"}', 5_000]]);\n });\n\n test(\"an omitted payload is sent as an empty object, not undefined\", async () => {\n let sent: string | undefined;\n install((_apiName: string, payloadJson: string) => {\n sent = payloadJson;\n return Promise.resolve(\"null\");\n });\n await getWorkerManager().call(\"status\");\n expect(sent).toBe(\"{}\");\n });\n\n test(\"a typed host error surfaces as a WorkerCallError carrying the tag\", async () => {\n install(() => Promise.resolve('{\"error\":\"unavailable\"}'));\n const error = await getWorkerManager()\n .call(\"startSettlement\")\n .catch((thrown: unknown) => thrown);\n expect(error).toBeInstanceOf(WorkerCallError);\n expect((error as WorkerCallError).tag).toBe(\"unavailable\");\n });\n\n test(\"an unrecognised error tag degrades to unavailable\", async () => {\n install(() => Promise.resolve('{\"error\":\"someFutureFailure\"}'));\n const error = await getWorkerManager()\n .call(\"startSettlement\")\n .catch((thrown: unknown) => thrown);\n expect((error as WorkerCallError).tag).toBe(\"unavailable\");\n });\n\n test(\"a non-JSON answer is invalid rather than a parse crash\", async () => {\n install(() => Promise.resolve(\"not json\"));\n const error = await getWorkerManager()\n .call(\"status\")\n .catch((thrown: unknown) => thrown);\n expect((error as WorkerCallError).tag).toBe(\"invalid\");\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Host chain discovery. Resolves chain roles to genesis hashes against the\n * host's configured environment instead of hard-coding them.\n *\n * The wire method takes one identifier per call, so the facade fires one\n * concurrent call per requested identifier and caches the combined result\n * for the lifetime of the connection. Consumed internally by chain-client.\n * Products normally never call this directly.\n *\n * @module\n */\n\nimport type {\n ChainIdentifier,\n HexString,\n TrUApiClient,\n VersionedRemoteChainInfoError,\n scale,\n} from \"@parity/truapi\";\nimport { createLogger } from \"@parity/product-sdk-logger\";\nimport { formatHostError } from \"./errors.js\";\nimport { getClient } from \"./transport.js\";\n\nconst log = createLogger(\"host\");\n\n/**\n * Chain-role identifier. A closed protocol enum, not a free-form name. The\n * host maps each role to the concrete chain of its configured environment.\n */\nexport type HostChainIdentifier = ChainIdentifier;\n\n/** The host's configured environment plus per-identifier resolved genesis hashes. */\nexport interface HostChainDiscovery {\n /** Ecosystem the host is configured for, e.g. `\"polkadot\"`, `\"paseo\"`. */\n network: string;\n /** Present for every requested identifier the host serves. */\n chains: Partial<Record<HostChainIdentifier, HexString>>;\n}\n\n/** Error channel of `chain.getChainInfo`. */\ntype GetChainInfoError = scale.CallErrorValue<VersionedRemoteChainInfoError>;\n\n/**\n * Marks a transient probe failure. These are evicted from the cache so the\n * next call re-probes. Stable \"no discovery\" answers stay cached.\n */\nconst TRANSIENT_FAILURE = Symbol(\"transient-failure\");\n\n/**\n * Hosts that predate the wire-id reservation never answer the probe at all,\n * so a silent host must resolve as \"no discovery\" instead of hanging. The\n * answer comes from host config with no chain I/O, so a short deadline is\n * enough. A timeout is treated as transient, never cached: a host that\n * supports discovery but started slowly would otherwise be recorded as\n * pre-discovery for the life of the client. The cost is that a genuinely\n * legacy host pays the deadline again on the next call.\n */\nconst PROBE_TIMEOUT_MS = 3_000;\n\nconst discoveryCache = new WeakMap<TrUApiClient, Map<string, Promise<HostChainDiscovery | null>>>();\n\n/**\n * Resolve chain roles against the current host.\n *\n * Returns `null` when discovery is unavailable: outside a container, on a\n * legacy host, or when the host serves none of the requested identifiers.\n * Callers treat `null` as \"fall back to configured constants\".\n *\n * One concurrent `getChainInfo` call is made per identifier. Identifiers\n * the host answers `NotSupported` for are absent from `chains`. Stable\n * answers are cached per client and identifier set. Unexpected wire failures\n * and probe timeouts are logged, return `null` and are not cached, so a later\n * call re-probes.\n */\nexport async function getHostChainInfo(\n identifiers: readonly HostChainIdentifier[],\n): Promise<HostChainDiscovery | null> {\n const client = await getClient();\n if (!client) return null;\n let bySet = discoveryCache.get(client);\n if (!bySet) {\n bySet = new Map();\n discoveryCache.set(client, bySet);\n }\n const key = [...identifiers].sort().join(\",\");\n let cached = bySet.get(key);\n if (!cached) {\n cached = fetchChainInfo(client, identifiers).then((result) => {\n if (result === TRANSIENT_FAILURE) {\n // Evict so the next caller re-probes.\n bySet.delete(key);\n return null;\n }\n return result;\n });\n bySet.set(key, cached);\n }\n return cached;\n}\n\nasync function fetchChainInfo(\n client: TrUApiClient,\n identifiers: readonly HostChainIdentifier[],\n): Promise<HostChainDiscovery | null | typeof TRANSIENT_FAILURE> {\n try {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const probe = Promise.all(\n identifiers.map((id) =>\n client.chain.getChainInfo({ chain: id }).match(\n (value) => ({ id, ok: value }) as const,\n (error) => ({ id, err: error }) as const,\n ),\n ),\n );\n const outcomes = await Promise.race([\n probe,\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), PROBE_TIMEOUT_MS);\n }),\n ]).finally(() => clearTimeout(timer));\n if (outcomes === \"timeout\") {\n log.warn(\"getChainInfo probe timed out, treating the host as pre-discovery for now\");\n return TRANSIENT_FAILURE;\n }\n let network: string | undefined;\n const chains: Partial<Record<HostChainIdentifier, HexString>> = {};\n for (const outcome of outcomes) {\n if (\"ok\" in outcome) {\n network = outcome.ok.network;\n chains[outcome.id] = outcome.ok.genesisHash;\n continue;\n }\n // \"Unsupported\" means the host predates the method entirely.\n // \"NotSupported\" means this one identifier is not served.\n if (outcome.err.tag === \"Unsupported\") return null;\n if (isNotSupported(outcome.err)) continue;\n log.warn(`getChainInfo failed: ${formatHostError(outcome.err)}`);\n return TRANSIENT_FAILURE;\n }\n // Every identifier was refused, so the host never revealed its network.\n if (network === undefined) return null;\n return { network, chains };\n } catch (error) {\n log.warn(`getChainInfo failed: ${formatHostError(error)}`);\n return TRANSIENT_FAILURE;\n }\n}\n\n/** True when a domain error is the unit `NotSupported` variant. */\nfunction isNotSupported(error: GetChainInfoError): boolean {\n return error.tag === \"Domain\" && error.value.value.tag === \"NotSupported\";\n}\n\nif (import.meta.vitest) {\n const { test, expect, afterEach, vi } = import.meta.vitest;\n const { setTruApiClient } = await import(\"./transport.js\");\n type ChainInfoResponse = import(\"@parity/truapi\").RemoteChainInfoResponse;\n\n type Served = Partial<Record<HostChainIdentifier, HexString>>;\n\n const NOT_SUPPORTED: GetChainInfoError = {\n tag: \"Domain\",\n value: { tag: \"V1\", value: { tag: \"NotSupported\" } },\n };\n\n type FakeBehavior = { network: string; served: Served } | { err: GetChainInfoError };\n\n /** Fake client answering from a served-chains map or a per-call behavior function. */\n function fakeClient(\n behavior: FakeBehavior | ((call: number) => FakeBehavior),\n calls: { count: number; requests: HostChainIdentifier[] } = { count: 0, requests: [] },\n ): TrUApiClient {\n return {\n chain: {\n getChainInfo: (request: { chain: HostChainIdentifier }) => {\n const current =\n typeof behavior === \"function\" ? behavior(calls.count) : behavior;\n calls.count += 1;\n calls.requests.push(request.chain);\n return {\n match: async <A, B>(\n onOk: (v: ChainInfoResponse) => A,\n onErr: (e: GetChainInfoError) => B,\n ) => {\n if (\"err\" in current) return onErr(current.err);\n const genesisHash = current.served[request.chain];\n if (!genesisHash) return onErr(NOT_SUPPORTED);\n return onOk({\n network: current.network,\n chain: request.chain,\n genesisHash,\n });\n },\n };\n },\n },\n } as unknown as TrUApiClient;\n }\n\n const PASEO_SERVED: Served = {\n AssetHub: \"0xaa\" as HexString,\n Bulletin: \"0xbb\" as HexString,\n People: \"0xcc\" as HexString,\n };\n\n afterEach(() => {\n setTruApiClient(null);\n vi.restoreAllMocks();\n });\n\n test(\"resolves each requested identifier once, unserved ones absent\", async () => {\n const calls = { count: 0, requests: [] as HostChainIdentifier[] };\n setTruApiClient(\n fakeClient({ network: \"paseo\", served: { AssetHub: \"0xaa\" as HexString } }, calls),\n );\n const result = await getHostChainInfo([\"AssetHub\", \"Bulletin\", \"People\"]);\n expect(result).toEqual({ network: \"paseo\", chains: { AssetHub: \"0xaa\" } });\n expect(calls.requests).toEqual([\"AssetHub\", \"Bulletin\", \"People\"]);\n });\n\n test(\"returns null when discovery is unavailable and caches the answer\", async () => {\n // Outside a container.\n expect(await getHostChainInfo([\"AssetHub\"])).toBeNull();\n // Every identifier refused, so the network is never revealed.\n const refused = { count: 0, requests: [] as HostChainIdentifier[] };\n setTruApiClient(fakeClient({ network: \"devnet\", served: {} }, refused));\n expect(await getHostChainInfo([\"Bulletin\"])).toBeNull();\n expect(await getHostChainInfo([\"Bulletin\"])).toBeNull();\n expect(refused.count).toBe(1);\n // Legacy host answering Unsupported.\n const legacy = { count: 0, requests: [] as HostChainIdentifier[] };\n setTruApiClient(fakeClient({ err: { tag: \"Unsupported\" } }, legacy));\n expect(await getHostChainInfo([\"AssetHub\"])).toBeNull();\n expect(await getHostChainInfo([\"AssetHub\"])).toBeNull();\n expect(legacy.count).toBe(1);\n });\n\n test(\"caches per client and identifier set, ignoring order\", async () => {\n const calls = { count: 0, requests: [] as HostChainIdentifier[] };\n setTruApiClient(fakeClient({ network: \"paseo\", served: PASEO_SERVED }, calls));\n await getHostChainInfo([\"AssetHub\", \"Bulletin\"]);\n await getHostChainInfo([\"Bulletin\", \"AssetHub\"]);\n expect(calls.count).toBe(2);\n await getHostChainInfo([\"People\"]);\n expect(calls.count).toBe(3);\n });\n\n test(\"a silent host times out to null and the next call re-probes\", async () => {\n vi.useFakeTimers();\n try {\n const calls = { count: 0 };\n setTruApiClient({\n chain: {\n getChainInfo: () => {\n calls.count += 1;\n return { match: () => new Promise(() => {}) };\n },\n },\n } as unknown as TrUApiClient);\n const pending = getHostChainInfo([\"AssetHub\"]);\n await vi.advanceTimersByTimeAsync(3_000);\n expect(await pending).toBeNull();\n // A host that merely started slowly must not stay classified as\n // pre-discovery, so the timeout is never cached.\n const retry = getHostChainInfo([\"AssetHub\"]);\n await vi.advanceTimersByTimeAsync(3_000);\n expect(await retry).toBeNull();\n expect(calls.count).toBe(2);\n } finally {\n vi.useRealTimers();\n }\n });\n\n test(\"transient wire failures return null but are not cached, the next call re-probes\", async () => {\n setTruApiClient(\n fakeClient((call) =>\n call === 0\n ? { err: { tag: \"HostFailure\", value: { reason: \"boom\" } } }\n : { network: \"paseo\", served: PASEO_SERVED },\n ),\n );\n expect(await getHostChainInfo([\"AssetHub\"])).toBeNull();\n expect((await getHostChainInfo([\"AssetHub\"]))?.network).toBe(\"paseo\");\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Host wallet accounts, backed by `truApi.account.*` and `truApi.signing.*`.\n *\n * `getAccountsProvider()` returns the full accounts surface — user identity\n * (`getUserId` / `requestLogin`), the user's existing wallet accounts\n * (`getLegacyAccounts`), app-scoped product accounts (`getProductAccount` /\n * `getProductAccountAlias`), Ring VRF proofs (`createRingVRFProof`), sr25519 VRF\n * signatures over a caller-supplied Merlin transcript (`signVrf`), connection\n * status, and PAPI `PolkadotSigner` factories for both product and legacy\n * accounts.\n *\n * The signer factories build a PAPI `PolkadotSigner` directly over\n * `truApi.signing.createTransaction` (product) /\n * `createTransactionWithLegacyAccount` (legacy) — `signTx` derives the\n * metadata-driven `txExtVersion` and maps the signed extensions to the host's\n * wire shape; `signBytes` calls `signing.signRaw(WithLegacyAccount)`. No PJS\n * bridge is involved, so opaque signed extensions (e.g. Paseo Next's `AsPgas`)\n * survive end-to-end.\n *\n * @module\n */\n\nimport { decAnyMetadata, unifyMetadata } from \"@polkadot-api/substrate-bindings\";\nimport type { ResultAsync } from \"neverthrow\";\nimport { AccountId, type PolkadotSigner } from \"polkadot-api\";\n\nimport type {\n ContextualAlias as WireAlias,\n HostAccountConnectionStatusSubscribeItem,\n HostAccountCreateProofResponse as WireRingVRFProof,\n HostRequestLoginResponse,\n LegacyAccount as WireLegacyAccount,\n ProductAccount as WireProductAccount,\n ProductAccountId,\n ProductProofContext,\n RegisteredRingVrfKey as WireRegisteredRingVrfKey,\n RingLocation,\n RingVrfKeyDisclosure,\n TrUApiClient,\n VersionedHostAccountCreateProofError,\n VersionedHostAccountGetAliasError,\n VersionedHostAccountGetError,\n VersionedHostAccountListRingVrfKeysError,\n VersionedHostAccountRegisterRingVrfKeyError,\n VersionedHostAccountRingVrfSignError,\n VersionedHostAccountSignVrfError,\n VersionedHostGetLegacyAccountsError,\n VersionedHostGetUserIdError,\n VersionedHostRequestLoginError,\n VrfSignature as WireVrfSignature,\n VrfTranscriptItem as WireVrfTranscriptItem,\n scale,\n} from \"@parity/truapi\";\n\nimport { getClient, subscribeWithInterrupt } from \"./transport.js\";\nimport { fromHex, toHex, unwrapHostResult } from \"./truapi.js\";\nimport type { HostSubscription } from \"./types.js\";\n\n/**\n * Ring VRF request shapes, re-exported from `@parity/truapi`:\n * - `RingLocation` — where the ring lives (`{ chainId, junctions }`; junctions\n * address the ring via `PalletInstance` / `CollectionId` steps).\n * - `ProductProofContext` — the product-scoped proof context\n * (`{ productId, suffix }`), expanded by the host into the 32-byte context a\n * proof or alias is bound to.\n * - `DerivationIndex` — the tagged selector `ProductProofContext.suffix`\n * carries: `{ tag: \"Index\", value: number }` for a plain index, or\n * `{ tag: \"Raw\", value: HexString }` for a raw 32-byte index.\n */\nexport type {\n DerivationIndex,\n ProductProofContext,\n RingLocation,\n RingVrfKeyDisclosure,\n} from \"@parity/truapi\";\n\n// The account/alias shapes come from `@parity/truapi`'s generated specs; we\n// derive the SDK-facing views from them so the field inventory tracks the\n// protocol automatically, and override only the fields the adapter re-encodes:\n// byte fields decoded from `0x`-prefixed `HexString`s to `Uint8Array`s, and\n// the tagged derivation-index selector kept as a plain `number` (wrapped back\n// into `Index` at the wire boundary). Shapes re-exported verbatim (e.g.\n// `ProductProofContext`) track the wire as-is. Same pattern as\n// `@parity/product-sdk-statement-store`.\n\n/**\n * One of the user's existing wallet accounts, surfaced through the host and\n * identified by its public key and an optional name. Contrast with\n * {@link ProductAccount}, which is also user-controlled but derived by the\n * host for a specific app rather than picked from the user's existing keys.\n *\n * Derived from `@parity/truapi`'s `LegacyAccount`, with `publicKey` decoded to bytes.\n */\nexport type HostAccount = Omit<WireLegacyAccount, \"publicKey\"> & {\n /** Raw public key bytes. */\n publicKey: Uint8Array;\n};\n\n/**\n * A product account — an app-scoped derived account managed by the host wallet.\n *\n * The host derives a unique keypair for each app (identified by `dotNsIdentifier`)\n * so apps get their own account that the user controls but is scoped to the app.\n *\n * Combines `@parity/truapi`'s `ProductAccountId` (the `{ dotNsIdentifier,\n * derivationIndex }` lookup key) with the `ProductAccount` payload, with\n * `publicKey` decoded to bytes and `derivationIndex` kept as the plain\n * numeric index (the adapter wraps it into the wire's tagged\n * {@link DerivationIndex} selector).\n */\nexport type ProductAccount = Omit<ProductAccountId, \"derivationIndex\"> &\n Omit<WireProductAccount, \"publicKey\"> & {\n /** Plain account index within the product subtree. */\n derivationIndex: number;\n /** Raw public key bytes. */\n publicKey: Uint8Array;\n };\n\n/**\n * How callers address a product account: app identifier plus an optional index,\n * defaulting to 0. A {@link ProductAccount} satisfies this, so an account from\n * {@link AccountsProvider.getProductAccount} can be passed straight back in.\n */\nexport type ProductAccountLookup = Omit<ProductAccountId, \"derivationIndex\"> & {\n /** Plain account index within the product subtree. Defaults to 0. */\n derivationIndex?: number;\n};\n\ndeclare const ringVrfKeyHandleBrand: unique symbol;\n\n/**\n * Opaque public name of a registered ring-VRF key.\n *\n * Handles come from {@link AccountsProvider.listRingVrfKeys}; product code\n * cannot construct one from a derivation index.\n */\nexport type RingVrfKeyHandle = {\n readonly [ringVrfKeyHandleBrand]: \"RingVrfKeyHandle\";\n};\n\n/** Ring-VRF member public key, decoded from the wire's hex string. */\nexport type RingVrfPublicKey = Uint8Array;\n\n/** Registered key metadata returned by the host. */\nexport type RegisteredRingVrfKey = Omit<WireRegisteredRingVrfKey, \"handle\" | \"publicKey\"> & {\n /** Opaque handle to pass back for alias and proof requests. */\n handle: RingVrfKeyHandle;\n /** Present when public-key disclosure was granted. */\n publicKey?: RingVrfPublicKey;\n};\n\nfunction sameRingLocation(a: RingLocation, b: RingLocation): boolean {\n if (\n a.chainId.toLowerCase() !== b.chainId.toLowerCase() ||\n a.junctions.length !== b.junctions.length\n ) {\n return false;\n }\n return a.junctions.every((junction, index) => {\n const candidate = b.junctions[index];\n if (junction.tag === \"PalletInstance\") {\n return candidate.tag === \"PalletInstance\" && junction.value === candidate.value;\n }\n return (\n candidate.tag === \"CollectionId\" &&\n junction.value.toLowerCase() === candidate.value.toLowerCase()\n );\n });\n}\n\n/**\n * Select a registered key by its declared ring and return its opaque handle.\n *\n * Consumers must not hard-code another product's derivation index. Registry\n * order breaks ties when an owner declares multiple keys for the same ring.\n */\nexport function findRingVrfKeyHandle(\n keys: RegisteredRingVrfKey[],\n ring: RingLocation,\n): RingVrfKeyHandle | undefined {\n return keys.find((key) => key.rings.some((candidate) => sameRingLocation(candidate, ring)))\n ?.handle;\n}\n\n/**\n * A contextual alias obtained from Ring VRF.\n *\n * Proves account membership in a ring without revealing which account.\n *\n * Derived from `@parity/truapi`'s `ContextualAlias`, with both fields decoded to bytes.\n */\nexport type ContextualAlias = { [K in keyof WireAlias]: Uint8Array };\n\n/**\n * A Ring VRF proof plus the values needed to verify it downstream (e.g.\n * against a precompile): the alias it commits to, and the ring member index /\n * revision the proof was generated against.\n *\n * Derived from `@parity/truapi`'s `HostAccountCreateProofResponse`, with the\n * byte fields decoded.\n */\nexport type RingVRFProof = Omit<WireRingVRFProof, \"proof\" | \"contextualAlias\"> & {\n /** Raw ring VRF proof bytes. */\n proof: Uint8Array;\n /** Alias derived for the request's context. */\n contextualAlias: ContextualAlias;\n};\n\n/**\n * One `append_message(label, value)` call replayed against a VRF transcript.\n * Merlin labels are ASCII by convention: use `utf8ToBytes(\"round\")`.\n *\n * Derived from `@parity/truapi`'s `VrfTranscriptItem`, decoded to bytes.\n */\nexport type VrfTranscriptItem = { [K in keyof WireVrfTranscriptItem]: Uint8Array };\n\n/**\n * An sr25519 VRF signature: the pre-output and its DLEQ proof.\n *\n * Derived from `@parity/truapi`'s `VrfSignature`, decoded to bytes.\n */\nexport type VrfSignature = { [K in keyof WireVrfSignature]: Uint8Array };\n\n/**\n * Accounts provider handle, backed by `truApi.account.*` / `truApi.signing.*`.\n * Surfaces the user's wallet accounts, app-scoped product accounts, Ring VRF,\n * user identity, connection status, and `PolkadotSigner` factories.\n *\n * Lookup methods return a neverthrow `ResultAsync` (use `.match(ok, err)`);\n * the signer factories return a synchronous PAPI `PolkadotSigner`. The `err`\n * channel carries truapi's canonical `CallErrorValue` envelope around the\n * per-call versioned domain error, exactly as the generated client returns it.\n */\nexport interface AccountsProvider {\n getUserId(): ResultAsync<\n { primaryUsername: string },\n scale.CallErrorValue<VersionedHostGetUserIdError>\n >;\n requestLogin(\n reason?: string,\n ): ResultAsync<HostRequestLoginResponse, scale.CallErrorValue<VersionedHostRequestLoginError>>;\n getProductAccount(\n dotNsIdentifier: string,\n derivationIndex?: number,\n ): ResultAsync<ProductAccount, scale.CallErrorValue<VersionedHostAccountGetError>>;\n /**\n * Register a ring-VRF key owned by the calling product.\n *\n * `index` is the plain derivation index within the product's ring-VRF\n * domain; the adapter wraps it into the wire's tagged selector.\n *\n * Registration returns the key's public key. Call {@link listRingVrfKeys}\n * afterward to obtain the opaque handle required by alias and proof calls.\n */\n registerRingVrfKey(\n index: number,\n ring: RingLocation,\n ): ResultAsync<\n RingVrfPublicKey,\n scale.CallErrorValue<VersionedHostAccountRegisterRingVrfKeyError>\n >;\n /** List an owner's registered ring-VRF keys. */\n listRingVrfKeys(\n owner: string,\n disclosure?: RingVrfKeyDisclosure,\n ): ResultAsync<\n RegisteredRingVrfKey[],\n scale.CallErrorValue<VersionedHostAccountListRingVrfKeysError>\n >;\n /** Derive a contextual alias with an explicitly registered ring-VRF key. */\n getProductAccountAlias(\n keyHandle: RingVrfKeyHandle,\n context: ProductProofContext,\n location: RingLocation,\n ): ResultAsync<ContextualAlias, scale.CallErrorValue<VersionedHostAccountGetAliasError>>;\n getLegacyAccounts(): ResultAsync<\n HostAccount[],\n scale.CallErrorValue<VersionedHostGetLegacyAccountsError>\n >;\n /**\n * Generate a Ring VRF proof with an explicitly registered key, binding\n * `message` to the product-scoped `context`.\n */\n createRingVRFProof(\n keyHandle: RingVrfKeyHandle,\n context: ProductProofContext,\n location: RingLocation,\n message: Uint8Array,\n ): ResultAsync<RingVRFProof, scale.CallErrorValue<VersionedHostAccountCreateProofError>>;\n /**\n * Sign `message` directly with an explicitly registered ring-VRF key.\n *\n * Unlike {@link createRingVRFProof} this proves nothing about ring\n * membership; it is the plain signature under the member key, for\n * protocols that carry their own proof.\n */\n ringVrfSign(\n keyHandle: RingVrfKeyHandle,\n message: Uint8Array,\n ): ResultAsync<Uint8Array, scale.CallErrorValue<VersionedHostAccountRingVrfSignError>>;\n /**\n * Produce an sr25519 VRF signature from a product account (RFC-0023).\n *\n * The host builds a Merlin transcript from `transcriptLabel` and `items`,\n * then signs it with the account's key. Unlike {@link createRingVRFProof},\n * this names the signing account instead of proving ring membership.\n *\n * The caller owns four things the types cannot enforce:\n *\n * - Domain separation. A label borrowed from another protocol makes the\n * output replayable across both.\n * - Freshness. The VRF is deterministic, so per-round values belong in\n * `items`.\n * - Size. Hosts cap the transcript at 32 items and 8 KiB total.\n * - Authorization. An `AutoSigning` allowance makes these calls silent. It\n * is not VRF-scoped, so it covers other signing by that account too.\n *\n * Hosts predating the call reject it through the error channel.\n */\n signVrf(\n account: ProductAccountLookup,\n transcriptLabel: Uint8Array,\n items: VrfTranscriptItem[],\n ): ResultAsync<VrfSignature, scale.CallErrorValue<VersionedHostAccountSignVrfError>>;\n /**\n * Build a `PolkadotSigner` for a product account. Signing routes through the\n * host's `createTransaction` path: the host decodes the metadata and forwards\n * the opaque signed-extension bytes, so unknown extensions survive end-to-end.\n */\n getProductAccountSigner(account: ProductAccount): PolkadotSigner;\n /**\n * Build a `PolkadotSigner` for one of the user's existing wallet accounts.\n * `name` is accepted for callsite ergonomics but unused — the signer is\n * derived from `publicKey` alone.\n */\n getLegacyAccountSigner(account: { publicKey: Uint8Array; name?: string }): PolkadotSigner;\n subscribeAccountConnectionStatus(\n callback: (status: HostAccountConnectionStatusSubscribeItem) => void,\n ): HostSubscription;\n}\n\n/**\n * Derive the host's extrinsic-extension version from SCALE-encoded metadata:\n * v4 → 0, otherwise the latest supported version. `unifyMetadata` normalizes\n * v14/v15 so `.extrinsic.version` is an array.\n *\n * Indirected through {@link deps} so the SCALE decode (which needs a real\n * metadata blob) can be stubbed in unit tests while the rest of the `signTx`\n * flow — genesis extraction, extension mapping, the host call — is exercised.\n */\nfunction deriveTxExtVersion(metadata: Uint8Array): number {\n const versions = unifyMetadata(decAnyMetadata(metadata)).extrinsic.version;\n if (versions.length === 0) {\n throw new Error(\"No extrinsic version found in metadata\");\n }\n const latestVersion = versions.reduce((acc, v) => Math.max(acc, v), 0);\n return latestVersion === 4 ? 0 : latestVersion;\n}\n\n/** Internal seam so `import.meta.vitest` can stub the metadata decode. @internal */\nconst deps = { deriveTxExtVersion };\n\n/**\n * Map a PAPI `signTx` call's signed extensions onto the host's\n * `TxPayloadExtension` wire shape (hex-encoded `extra` / `additionalSigned`).\n */\nfunction toHostExtensions(\n signedExtensions: Record<\n string,\n { identifier: string; value: Uint8Array; additionalSigned: Uint8Array }\n >,\n) {\n return Object.values(signedExtensions).map((ext) => ({\n id: ext.identifier,\n extra: toHex(ext.value),\n additionalSigned: toHex(ext.additionalSigned),\n }));\n}\n\n/**\n * Build the wire `ProductAccountId`: default the index to 0, wrap it as `Index`.\n *\n * Destructured rather than spread, so passing a full {@link ProductAccount}\n * cannot leak its `publicKey` onto the wire.\n */\nfunction toWireProductAccountId({\n dotNsIdentifier,\n derivationIndex = 0,\n}: ProductAccountLookup): ProductAccountId {\n return { dotNsIdentifier, derivationIndex: { tag: \"Index\", value: derivationIndex } };\n}\n\n/** Build an {@link AccountsProvider} over a TruAPI client's `account` / `signing` domains. */\nfunction adaptAccountsProvider(client: TrUApiClient): AccountsProvider {\n const account = client.account;\n const signing = client.signing;\n\n return {\n getUserId() {\n return account.getUserId().map((response) => ({\n primaryUsername: response.primaryUsername,\n }));\n },\n requestLogin(reason) {\n return account.requestLogin({ reason });\n },\n getProductAccount(dotNsIdentifier, derivationIndex = 0) {\n return account\n .getAccount({\n productAccountId: toWireProductAccountId({ dotNsIdentifier, derivationIndex }),\n })\n .map((response) => ({\n publicKey: fromHex(response.account.publicKey),\n dotNsIdentifier,\n derivationIndex,\n }));\n },\n registerRingVrfKey(index, ring) {\n return account\n .registerRingVrfKey({ index: { tag: \"Index\", value: index }, ring })\n .map(fromHex);\n },\n listRingVrfKeys(owner, disclosure = \"Anonymized\") {\n return account.listRingVrfKeys({ owner, disclosure }).map((keys) =>\n keys.map((key) => ({\n ...key,\n handle: key.handle as unknown as RingVrfKeyHandle,\n publicKey: key.publicKey === undefined ? undefined : fromHex(key.publicKey),\n })),\n );\n },\n getProductAccountAlias(keyHandle, context, location) {\n return account\n .getAccountAlias({\n keyHandle: keyHandle as unknown as ProductAccountId,\n context,\n ringLocation: location,\n })\n .map((response) => ({\n context: fromHex(response.context),\n alias: fromHex(response.alias),\n }));\n },\n getLegacyAccounts() {\n return account.getLegacyAccounts().map((response) =>\n response.accounts.map((a) => ({\n publicKey: fromHex(a.publicKey),\n name: a.name,\n })),\n );\n },\n createRingVRFProof(keyHandle, context, location, message) {\n return account\n .createAccountProof({\n keyHandle: keyHandle as unknown as ProductAccountId,\n context,\n ringLocation: location,\n message: toHex(message),\n })\n .map((response) => ({\n proof: fromHex(response.proof),\n contextualAlias: {\n context: fromHex(response.contextualAlias.context),\n alias: fromHex(response.contextualAlias.alias),\n },\n ringIndex: response.ringIndex,\n ringRevision: response.ringRevision,\n }));\n },\n ringVrfSign(keyHandle, message) {\n return account\n .ringVrfSign({\n keyHandle: keyHandle as unknown as ProductAccountId,\n message: toHex(message),\n })\n .map(fromHex);\n },\n signVrf(account_, transcriptLabel, items) {\n return account\n .signVrf({\n account: toWireProductAccountId(account_),\n transcriptLabel: toHex(transcriptLabel),\n items: items.map(({ label, value }) => ({\n label: toHex(label),\n value: toHex(value),\n })),\n })\n .map((response) => ({\n preOutput: fromHex(response.preOutput),\n proof: fromHex(response.proof),\n }));\n },\n getProductAccountSigner(account_) {\n const productAccountId = toWireProductAccountId(account_);\n\n return {\n publicKey: account_.publicKey,\n async signTx(callData, signedExtensions, metadata) {\n const checkGenesis = signedExtensions.CheckGenesis;\n if (!checkGenesis) {\n throw new Error(\"Can't find genesis hash on transaction\");\n }\n\n const response = await unwrapHostResult(\n signing.createTransaction({\n signer: productAccountId,\n genesisHash: toHex(checkGenesis.additionalSigned),\n callData: toHex(callData),\n extensions: toHostExtensions(signedExtensions),\n txExtVersion: deps.deriveTxExtVersion(metadata),\n }),\n \"createTransaction failed\",\n );\n return fromHex(response.transaction);\n },\n async signBytes(data) {\n const response = await unwrapHostResult(\n signing.signRaw({\n account: productAccountId,\n payload: { tag: \"Bytes\", value: { bytes: toHex(data) } },\n }),\n \"signRaw failed\",\n );\n return fromHex(response.signature);\n },\n };\n },\n getLegacyAccountSigner(account_) {\n // `createTransactionWithLegacyAccount` identifies the signer by its\n // raw account id (hex public key); `signRawWithLegacyAccount` takes an\n // SS58 address the wallet can match. Compute both up front.\n const signerHex = toHex(account_.publicKey);\n const ss58Address = AccountId().dec(account_.publicKey);\n\n return {\n publicKey: account_.publicKey,\n async signTx(callData, signedExtensions, metadata) {\n const checkGenesis = signedExtensions.CheckGenesis;\n if (!checkGenesis) {\n throw new Error(\"Can't find genesis hash on transaction\");\n }\n\n const response = await unwrapHostResult(\n signing.createTransactionWithLegacyAccount({\n signer: signerHex,\n genesisHash: toHex(checkGenesis.additionalSigned),\n callData: toHex(callData),\n extensions: toHostExtensions(signedExtensions),\n txExtVersion: deps.deriveTxExtVersion(metadata),\n }),\n \"createTransactionWithLegacyAccount failed\",\n );\n return fromHex(response.transaction);\n },\n async signBytes(data) {\n const response = await unwrapHostResult(\n signing.signRawWithLegacyAccount({\n signer: ss58Address,\n payload: { tag: \"Bytes\", value: { bytes: toHex(data) } },\n }),\n \"signRawWithLegacyAccount failed\",\n );\n return fromHex(response.signature);\n },\n };\n },\n subscribeAccountConnectionStatus(callback) {\n return subscribeWithInterrupt(account.connectionStatusSubscribe(), callback);\n },\n };\n}\n\n/**\n * Get the accounts provider for managing host accounts, backed by\n * `truApi.account.*` / `truApi.signing.*`. Returns `null` when running outside\n * a host container.\n *\n * @returns The accounts provider, or `null` if unavailable.\n */\nexport async function getAccountsProvider(): Promise<AccountsProvider | null> {\n const client = await getClient();\n return client ? adaptAccountsProvider(client) : null;\n}\n\nif (import.meta.vitest) {\n const { test, expect, vi } = import.meta.vitest;\n\n /** Minimal fake of the truapi account/signing domains used to test the adapter. */\n function makeFakeClient(opts: { onCall?: (method: string, args: unknown) => void } = {}) {\n const okMatch = (value: unknown) => ({\n // neverthrow ResultAsync surface used by the adapter: .map + .match.\n map: (fn: (v: unknown) => unknown) => okMatch(fn(value)),\n match: (ok: (v: unknown) => unknown, _err: (e: unknown) => unknown) => ok(value),\n });\n const method = (name: string, response: unknown) => (args: unknown) => {\n opts.onCall?.(name, args);\n return okMatch(response);\n };\n return {\n account: {\n getUserId: method(\"getUserId\", { primaryUsername: \"alice.dot\" }),\n getAccount: method(\"getAccount\", { account: { publicKey: \"0xaa\" } }),\n registerRingVrfKey: method(\"registerRingVrfKey\", \"0x0304\"),\n ringVrfSign: method(\"ringVrfSign\", \"0xba5eba11\"),\n listRingVrfKeys: method(\"listRingVrfKeys\", [\n {\n handle: {\n dotNsIdentifier: \"people.dot\",\n derivationIndex: { tag: \"Index\", value: 0 },\n },\n rings: [\n {\n chainId: \"0x01\",\n junctions: [{ tag: \"PalletInstance\", value: 1 }],\n },\n ],\n },\n {\n handle: {\n dotNsIdentifier: \"people.dot\",\n derivationIndex: { tag: \"Index\", value: 1 },\n },\n rings: [\n {\n chainId: \"0x02\",\n junctions: [{ tag: \"CollectionId\", value: \"0xaabb\" }],\n },\n ],\n publicKey: \"0x0102\",\n },\n ]),\n getAccountAlias: method(\"getAccountAlias\", { context: \"0x01\", alias: \"0x02\" }),\n getLegacyAccounts: method(\"getLegacyAccounts\", {\n accounts: [{ publicKey: \"0xbb\", name: \"Bob\" }],\n }),\n createAccountProof: method(\"createAccountProof\", {\n proof: \"0xc0ffee\",\n contextualAlias: { context: \"0x01\", alias: \"0x02\" },\n ringIndex: 3,\n ringRevision: 7,\n }),\n signVrf: method(\"signVrf\", { preOutput: \"0xaa11\", proof: \"0xbb22\" }),\n connectionStatusSubscribe: () => ({\n subscribe: () => ({ unsubscribe: vi.fn() }),\n [Symbol.observable as symbol]() {\n return this;\n },\n }),\n },\n signing: {\n createTransaction: method(\"createTransaction\", { transaction: \"0xdead\" }),\n createTransactionWithLegacyAccount: method(\"createTransactionWithLegacyAccount\", {\n transaction: \"0xfeed\",\n }),\n signRaw: method(\"signRaw\", { signature: \"0xbeef\" }),\n signRawWithLegacyAccount: method(\"signRawWithLegacyAccount\", {\n signature: \"0xcafe\",\n }),\n },\n } as unknown as TrUApiClient;\n }\n\n test(\"getAccountsProvider returns null outside a container\", async () => {\n expect(await getAccountsProvider()).toBeNull();\n });\n\n test(\"getProductAccount decodes the public key and carries the identifier\", async () => {\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n const account = await provider.getProductAccount(\"app.dot\", 2).match(\n (a) => a,\n () => null,\n );\n expect(calls[0]).toEqual([\n \"getAccount\",\n {\n productAccountId: {\n dotNsIdentifier: \"app.dot\",\n derivationIndex: { tag: \"Index\", value: 2 },\n },\n },\n ]);\n expect(account).toEqual({\n publicKey: fromHex(\"0xaa\"),\n dotNsIdentifier: \"app.dot\",\n derivationIndex: 2,\n });\n });\n\n test(\"getProductAccount defaults the derivation index in both the request and the result\", async () => {\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n const account = await provider.getProductAccount(\"app.dot\").match(\n (a) => a,\n () => null,\n );\n expect(calls[0]).toEqual([\n \"getAccount\",\n {\n productAccountId: {\n dotNsIdentifier: \"app.dot\",\n derivationIndex: { tag: \"Index\", value: 0 },\n },\n },\n ]);\n // The resolved index must reach the caller too, not just the wire.\n expect(account?.derivationIndex).toBe(0);\n });\n\n test(\"registerRingVrfKey wraps the numeric index and decodes the public key\", async () => {\n const calls: Array<[string, unknown]> = [];\n const provider = adaptAccountsProvider(\n makeFakeClient({ onCall: (method, args) => calls.push([method, args]) }),\n );\n const ring: RingLocation = {\n chainId: \"0x01\",\n junctions: [{ tag: \"PalletInstance\", value: 67 }],\n };\n const index = 2;\n const publicKey = await provider.registerRingVrfKey(index, ring).match(\n (value) => value,\n () => null,\n );\n\n expect(calls[0]).toEqual([\n \"registerRingVrfKey\",\n { index: { tag: \"Index\", value: 2 }, ring },\n ]);\n expect(publicKey).toEqual(fromHex(\"0x0304\"));\n });\n\n test(\"listRingVrfKeys selects by ring without exposing a raw index\", async () => {\n const calls: Array<[string, unknown]> = [];\n const provider = adaptAccountsProvider(\n makeFakeClient({ onCall: (method, args) => calls.push([method, args]) }),\n );\n const keys = await provider.listRingVrfKeys(\"people.dot\", \"PublicKey\").match(\n (value) => value,\n () => [],\n );\n expect(calls[0]).toEqual([\n \"listRingVrfKeys\",\n { owner: \"people.dot\", disclosure: \"PublicKey\" },\n ]);\n expect(keys[1].publicKey).toEqual(fromHex(\"0x0102\"));\n expect(\n findRingVrfKeyHandle(keys, {\n chainId: \"0x02\",\n junctions: [{ tag: \"CollectionId\", value: \"0xAABB\" }],\n }),\n ).toEqual(keys[1].handle);\n });\n\n test(\"getProductAccountAlias passes the selected key handle\", async () => {\n const calls: Array<[string, unknown]> = [];\n const provider = adaptAccountsProvider(\n makeFakeClient({ onCall: (method, args) => calls.push([method, args]) }),\n );\n const keys = await provider.listRingVrfKeys(\"people.dot\").match(\n (value) => value,\n () => [],\n );\n calls.length = 0;\n const keyHandle = keys[1].handle;\n const context: ProductProofContext = {\n productId: \"app.dot\",\n suffix: { tag: \"Index\", value: 0 },\n };\n const ring: RingLocation = {\n chainId: \"0x01\",\n junctions: [{ tag: \"PalletInstance\", value: 1 }],\n };\n const alias = await provider.getProductAccountAlias(keyHandle, context, ring).match(\n (value) => value,\n () => null,\n );\n expect(calls[0]).toEqual([\"getAccountAlias\", { keyHandle, context, ringLocation: ring }]);\n expect(alias).toEqual({ context: fromHex(\"0x01\"), alias: fromHex(\"0x02\") });\n });\n\n test(\"ringVrfSign passes the selected handle and decodes the signature\", async () => {\n const calls: Array<[string, unknown]> = [];\n const provider = adaptAccountsProvider(\n makeFakeClient({ onCall: (method, args) => calls.push([method, args]) }),\n );\n const keys = await provider.listRingVrfKeys(\"people.dot\").match(\n (value) => value,\n () => [],\n );\n calls.length = 0;\n const keyHandle = keys[1].handle;\n const signature = await provider.ringVrfSign(keyHandle, new Uint8Array([1, 2, 3])).match(\n (value) => value,\n () => null,\n );\n expect(calls[0]).toEqual([\n \"ringVrfSign\",\n { keyHandle, message: toHex(new Uint8Array([1, 2, 3])) },\n ]);\n expect(signature).toEqual(fromHex(\"0xba5eba11\"));\n });\n\n test(\"createRingVRFProof hex-encodes the message and decodes the proof response\", async () => {\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n const keyHandle = (\n await provider.listRingVrfKeys(\"people.dot\").match(\n (value) => value,\n () => [],\n )\n )[0].handle;\n calls.length = 0;\n const proof = await provider\n .createRingVRFProof(\n keyHandle,\n { productId: \"app.dot\", suffix: { tag: \"Index\", value: 0 } },\n { chainId: \"0x01\", junctions: [{ tag: \"PalletInstance\", value: 1 }] },\n new Uint8Array([1, 2, 3]),\n )\n .match(\n (p) => p,\n () => null,\n );\n expect(calls[0][0]).toBe(\"createAccountProof\");\n expect(calls[0][1]).toEqual({\n keyHandle: {\n dotNsIdentifier: \"people.dot\",\n derivationIndex: { tag: \"Index\", value: 0 },\n },\n context: { productId: \"app.dot\", suffix: { tag: \"Index\", value: 0 } },\n ringLocation: { chainId: \"0x01\", junctions: [{ tag: \"PalletInstance\", value: 1 }] },\n message: toHex(new Uint8Array([1, 2, 3])),\n });\n expect(proof).toEqual({\n proof: fromHex(\"0xc0ffee\"),\n contextualAlias: { context: fromHex(\"0x01\"), alias: fromHex(\"0x02\") },\n ringIndex: 3,\n ringRevision: 7,\n });\n });\n\n test(\"signVrf hex-encodes the transcript and decodes the signature\", async () => {\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n const transcriptLabel = new Uint8Array([1, 2, 3]);\n const itemLabel = new Uint8Array([4]);\n const itemValue = new Uint8Array([5, 6]);\n const signature = await provider\n .signVrf({ dotNsIdentifier: \"app.dot\", derivationIndex: 3 }, transcriptLabel, [\n { label: itemLabel, value: itemValue },\n ])\n .match(\n (s) => s,\n () => null,\n );\n expect(calls[0]).toEqual([\n \"signVrf\",\n {\n account: {\n dotNsIdentifier: \"app.dot\",\n derivationIndex: { tag: \"Index\", value: 3 },\n },\n transcriptLabel: toHex(transcriptLabel),\n items: [{ label: toHex(itemLabel), value: toHex(itemValue) }],\n },\n ]);\n expect(signature).toEqual({ preOutput: fromHex(\"0xaa11\"), proof: fromHex(\"0xbb22\") });\n });\n\n test(\"signVrf defaults the derivation index\", async () => {\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n await provider.signVrf({ dotNsIdentifier: \"app.dot\" }, new Uint8Array([1]), []).match(\n (s) => s,\n () => null,\n );\n expect((calls[0][1] as { account: unknown }).account).toEqual({\n dotNsIdentifier: \"app.dot\",\n derivationIndex: { tag: \"Index\", value: 0 },\n });\n });\n\n test(\"signVrf sends only the id fields when given a full product account\", async () => {\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n const account: ProductAccount = {\n dotNsIdentifier: \"app.dot\",\n derivationIndex: 1,\n publicKey: new Uint8Array(32).fill(0xaa),\n };\n await provider.signVrf(account, new Uint8Array([1]), []).match(\n (s) => s,\n () => null,\n );\n expect(Object.keys((calls[0][1] as { account: object }).account)).toEqual([\n \"dotNsIdentifier\",\n \"derivationIndex\",\n ]);\n });\n\n test(\"the product signer signs bytes via signing.signRaw\", async () => {\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n const signer = provider.getProductAccountSigner({\n dotNsIdentifier: \"app.dot\",\n derivationIndex: 0,\n publicKey: new Uint8Array(32).fill(0xaa),\n });\n const signature = await signer.signBytes(new Uint8Array([9, 9]));\n expect(calls.at(-1)).toEqual([\n \"signRaw\",\n {\n account: {\n dotNsIdentifier: \"app.dot\",\n derivationIndex: { tag: \"Index\", value: 0 },\n },\n payload: { tag: \"Bytes\", value: { bytes: toHex(new Uint8Array([9, 9])) } },\n },\n ]);\n expect(signature).toEqual(fromHex(\"0xbeef\"));\n });\n\n test(\"the legacy signer signs bytes via signing.signRawWithLegacyAccount (by SS58 address)\", async () => {\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n const publicKey = new Uint8Array(32).fill(0xbb);\n const signer = provider.getLegacyAccountSigner({ publicKey });\n const signature = await signer.signBytes(new Uint8Array([7, 7]));\n // signRawWithLegacyAccount identifies the signer by SS58 address, not raw pubkey.\n expect(calls.at(-1)).toEqual([\n \"signRawWithLegacyAccount\",\n {\n signer: AccountId().dec(publicKey),\n payload: { tag: \"Bytes\", value: { bytes: toHex(new Uint8Array([7, 7])) } },\n },\n ]);\n expect(signature).toEqual(fromHex(\"0xcafe\"));\n });\n\n test(\"the legacy signer's signTx throws without a CheckGenesis extension\", async () => {\n const provider = adaptAccountsProvider(makeFakeClient());\n const signer = provider.getLegacyAccountSigner({\n publicKey: new Uint8Array(32).fill(0xbb),\n });\n await expect(signer.signTx(new Uint8Array([1]), {}, new Uint8Array(), 0)).rejects.toThrow(\n \"Can't find genesis hash on transaction\",\n );\n });\n\n // Signed extensions PAPI hands to `signTx`. `CheckGenesis.additionalSigned`\n // carries the genesis hash the signer pulls out; the rest are mapped to the\n // host's `{ id, extra, additionalSigned }` wire shape.\n const sampleExtensions = {\n CheckGenesis: {\n identifier: \"CheckGenesis\",\n value: new Uint8Array([]),\n additionalSigned: new Uint8Array([0x01, 0x02]),\n },\n CheckNonce: {\n identifier: \"CheckNonce\",\n value: new Uint8Array([0x05]),\n additionalSigned: new Uint8Array([]),\n },\n };\n const expectedHostExtensions = [\n {\n id: \"CheckGenesis\",\n extra: toHex(new Uint8Array([])),\n additionalSigned: toHex(new Uint8Array([0x01, 0x02])),\n },\n {\n id: \"CheckNonce\",\n extra: toHex(new Uint8Array([0x05])),\n additionalSigned: toHex(new Uint8Array([])),\n },\n ];\n\n test(\"the product signer's signTx builds createTransaction from genesis + extensions\", async () => {\n // Stub the metadata decode (needs a real SCALE blob) so the rest of the\n // signTx flow — genesis extraction, extension mapping, the host call,\n // response decode — is exercised against a fixed txExtVersion.\n vi.spyOn(deps, \"deriveTxExtVersion\").mockReturnValue(0);\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n const signer = provider.getProductAccountSigner({\n dotNsIdentifier: \"app.dot\",\n derivationIndex: 0,\n publicKey: new Uint8Array(32).fill(0xaa),\n });\n\n const signed = await signer.signTx(\n new Uint8Array([0xca, 0x11]),\n sampleExtensions,\n new Uint8Array([0x6d]),\n 0,\n );\n\n expect(calls.at(-1)).toEqual([\n \"createTransaction\",\n {\n signer: { dotNsIdentifier: \"app.dot\", derivationIndex: { tag: \"Index\", value: 0 } },\n genesisHash: toHex(new Uint8Array([0x01, 0x02])),\n callData: toHex(new Uint8Array([0xca, 0x11])),\n extensions: expectedHostExtensions,\n txExtVersion: 0,\n },\n ]);\n expect(signed).toEqual(fromHex(\"0xdead\"));\n vi.restoreAllMocks();\n });\n\n test(\"the legacy signer's signTx builds createTransactionWithLegacyAccount (signer = hex pubkey)\", async () => {\n vi.spyOn(deps, \"deriveTxExtVersion\").mockReturnValue(0);\n const calls: Array<[string, unknown]> = [];\n const client = makeFakeClient({ onCall: (m, a) => calls.push([m, a]) });\n const provider = adaptAccountsProvider(client);\n const publicKey = new Uint8Array(32).fill(0xbb);\n const signer = provider.getLegacyAccountSigner({ publicKey });\n\n const signed = await signer.signTx(\n new Uint8Array([0xca, 0x11]),\n sampleExtensions,\n new Uint8Array([0x6d]),\n 0,\n );\n\n expect(calls.at(-1)).toEqual([\n \"createTransactionWithLegacyAccount\",\n {\n // createTransactionWithLegacyAccount identifies the signer by raw hex pubkey.\n signer: toHex(publicKey),\n genesisHash: toHex(new Uint8Array([0x01, 0x02])),\n callData: toHex(new Uint8Array([0xca, 0x11])),\n extensions: expectedHostExtensions,\n txExtVersion: 0,\n },\n ]);\n expect(signed).toEqual(fromHex(\"0xfeed\"));\n vi.restoreAllMocks();\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Higher-level wrappers for the host's single-permission flows.\n *\n * `truApi.permissions.requestRemotePermission` / `requestDevicePermission`\n * return a neverthrow `ResultAsync` of a `{ granted }` response.\n * {@link requestPermission} and {@link requestDevicePermission} collapse that\n * to one-liners returning a `Result<boolean, HostError>` — the granted flag on\n * success, a typed {@link HostError} on the `err` channel.\n *\n * @module\n */\n\nimport type { HostDevicePermissionRequest } from \"@parity/truapi\";\nimport { createLogger } from \"@parity/product-sdk-logger\";\n\nimport { type HostError, HostUnavailableError } from \"./errors.js\";\nimport { type Result, err } from \"./result.js\";\nimport { getTruApi, mapHostResult, type RemotePermission } from \"./truapi.js\";\n\nconst log = createLogger(\"host:permissions\");\n\n/**\n * Device permission the dapp can ask the host to grant via\n * {@link requestDevicePermission}. A string union (`\"Camera\"`, `\"Microphone\"`,\n * …) re-exported from `@parity/truapi`.\n */\nexport type DevicePermissionKind = HostDevicePermissionRequest;\n\n/**\n * Legacy alias of {@link RemotePermission}, kept for back-compat with code that\n * used the older name. Use either freely.\n */\nexport type RemotePermissionItem = RemotePermission;\n\n/**\n * Request a single remote permission from the host.\n *\n * Calls `truApi.permissions.requestRemotePermission` and returns the host's\n * boolean granted/denied outcome.\n *\n * @param permission - The remote permission to request.\n * @returns `ok(true)` if the host granted the permission, `ok(false)` if denied,\n * or `err(HostUnavailableError | HostCallFailedError)`.\n *\n * @example\n * ```ts\n * const r = await requestPermission({ tag: \"ChainSubmit\", value: undefined });\n * if (!r.ok || !r.value) {\n * tellUserToReconnect();\n * }\n * ```\n */\nexport async function requestPermission(\n permission: RemotePermission,\n): Promise<Result<boolean, HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n return err(new HostUnavailableError(\"requestPermission: TruAPI unavailable\"));\n }\n log.debug(\"requestPermission\", { tag: permission.tag });\n\n return mapHostResult(\n truApi.permissions.requestRemotePermission({ permission }),\n (response) => response.granted,\n \"requestPermission failed\",\n );\n}\n\n/**\n * Request a single device permission (camera, microphone, etc.) from the\n * host.\n *\n * Calls `truApi.permissions.requestDevicePermission` and returns the host's\n * boolean granted/denied outcome.\n *\n * @param permission - The device permission to request.\n * @returns `ok(true)` if the host granted the permission, `ok(false)` if denied,\n * or `err(HostUnavailableError | HostCallFailedError)`.\n *\n * @example\n * ```ts\n * const r = await requestDevicePermission(\"Camera\");\n * if (!r.ok || !r.value) {\n * showCameraDeniedMessage();\n * }\n * ```\n */\nexport async function requestDevicePermission(\n permission: DevicePermissionKind,\n): Promise<Result<boolean, HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n return err(new HostUnavailableError(\"requestDevicePermission: TruAPI unavailable\"));\n }\n log.debug(\"requestDevicePermission\", { permission });\n\n return mapHostResult(\n truApi.permissions.requestDevicePermission(permission),\n (response) => response.granted,\n \"requestDevicePermission failed\",\n );\n}\n\nif (import.meta.vitest) {\n const { test, expect, describe, vi } = import.meta.vitest;\n\n function okAsync<T>(value: T) {\n return { match: async (onOk: (v: T) => unknown) => onOk(value) };\n }\n function errAsync<E>(error: E) {\n return {\n match: async (_onOk: (v: unknown) => unknown, onErr: (e: E) => unknown) => onErr(error),\n };\n }\n\n async function withMockedTruApi<T>(\n client: unknown,\n fn: (mod: typeof import(\"./permissions.js\")) => Promise<T>,\n ): Promise<T> {\n vi.resetModules();\n vi.doMock(\"./truapi.js\", async (importOriginal) => {\n const original = await importOriginal<typeof import(\"./truapi.js\")>();\n return { ...original, getTruApi: async () => client };\n });\n try {\n const mod = await import(\"./permissions.js\");\n return await fn(mod);\n } finally {\n vi.doUnmock(\"./truapi.js\");\n vi.resetModules();\n }\n }\n\n describe(\"requestPermission\", () => {\n test(\"returns err(HostUnavailableError) when TruAPI is unavailable\", async () => {\n await withMockedTruApi(null, async (mod) => {\n const result = await mod.requestPermission({\n tag: \"ChainSubmit\",\n value: undefined,\n });\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostUnavailableError\");\n }\n });\n });\n\n test(\"returns ok with the granted flag\", async () => {\n await withMockedTruApi(\n {\n permissions: {\n requestRemotePermission: vi.fn(() => okAsync({ granted: true })),\n },\n },\n async (mod) => {\n const result = await mod.requestPermission({\n tag: \"ChainSubmit\",\n value: undefined,\n });\n expect(result).toEqual({ ok: true, value: true });\n },\n );\n });\n\n test(\"wraps host errors in err(HostCallFailedError) with a diagnostic message\", async () => {\n await withMockedTruApi(\n {\n permissions: {\n requestRemotePermission: vi.fn(() => errAsync({ reason: \"boom\" })),\n },\n },\n async (mod) => {\n const result = await mod.requestPermission({\n tag: \"ChainSubmit\",\n value: undefined,\n });\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostCallFailedError\");\n expect(result.error.message).toMatch(/requestPermission failed: boom/);\n }\n },\n );\n });\n });\n\n describe(\"requestDevicePermission\", () => {\n test(\"returns err(HostUnavailableError) when TruAPI is unavailable\", async () => {\n await withMockedTruApi(null, async (mod) => {\n const result = await mod.requestDevicePermission(\"Camera\");\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostUnavailableError\");\n }\n });\n });\n\n test(\"returns ok with the granted flag\", async () => {\n await withMockedTruApi(\n {\n permissions: {\n requestDevicePermission: vi.fn(() => okAsync({ granted: true })),\n },\n },\n async (mod) => {\n expect(await mod.requestDevicePermission(\"Camera\")).toEqual({\n ok: true,\n value: true,\n });\n },\n );\n });\n\n test(\"wraps host errors in err(HostCallFailedError) with a diagnostic message\", async () => {\n await withMockedTruApi(\n {\n permissions: {\n requestDevicePermission: vi.fn(() => errAsync({ reason: \"boom\" })),\n },\n },\n async (mod) => {\n const result = await mod.requestDevicePermission(\"Camera\");\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostCallFailedError\");\n expect(result.error.message).toMatch(\n /requestDevicePermission failed: boom/,\n );\n }\n },\n );\n });\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Higher-level wrapper for the host's theme subscription, backed by\n * `truApi.theme.subscribe`.\n *\n * `getThemeProvider` returns a handle whose `subscribeTheme(cb)` delivers a\n * typed {@link ThemeMode} — a `{ name, variant }` struct where `variant` is\n * `\"Light\" | \"Dark\"` and `name` is `{ tag: \"Default\" }` or\n * `{ tag: \"Custom\", value }` — and yields a {@link HostSubscription}\n * (`unsubscribe` + `onInterrupt`).\n *\n * @module\n */\n\nimport type { HostThemeSubscribeItem, TrUApiClient } from \"@parity/truapi\";\n\nimport { getClient, subscribeWithInterrupt } from \"./transport.js\";\nimport type { HostSubscription } from \"./types.js\";\n\n/**\n * Host theme value. A `{ name, variant }` struct re-exported from\n * `@parity/truapi`.\n */\nexport type ThemeMode = HostThemeSubscribeItem;\n\n/** Light/dark variant of the active theme (`\"Light\" | \"Dark\"`) and the active theme name. Re-exported from `@parity/truapi`. */\nexport type { ThemeName, ThemeVariant } from \"@parity/truapi\";\n\n/**\n * Host theme provider handle. `subscribeTheme(callback)` receives a typed\n * {@link ThemeMode} on every change and returns a {@link HostSubscription}.\n */\nexport interface ThemeProvider {\n subscribeTheme(callback: (theme: ThemeMode) => void): HostSubscription;\n}\n\n/** Build a {@link ThemeProvider} over a TruAPI client's `theme` domain. */\nfunction adaptThemeProvider(client: TrUApiClient): ThemeProvider {\n return {\n subscribeTheme(callback) {\n return subscribeWithInterrupt(client.theme.subscribe(), callback);\n },\n };\n}\n\n/**\n * Get the host theme provider, backed by `truApi.theme.*`. Returns `null` when\n * running outside a host container.\n *\n * @returns The theme provider, or `null` if unavailable.\n *\n * @example\n * ```ts\n * import { getThemeProvider } from \"@parity/product-sdk-host\";\n *\n * const provider = await getThemeProvider();\n * if (provider) {\n * const sub = provider.subscribeTheme((theme) => {\n * document.documentElement.dataset.theme = theme.variant.toLowerCase();\n * if (theme.name.tag === \"Custom\") loadCustomTheme(theme.name.value);\n * });\n * // sub.unsubscribe() to stop listening\n * }\n * ```\n */\nexport async function getThemeProvider(): Promise<ThemeProvider | null> {\n const client = await getClient();\n return client ? adaptThemeProvider(client) : null;\n}\n\nif (import.meta.vitest) {\n const { test, expect } = import.meta.vitest;\n\n test(\"getThemeProvider returns null outside a container\", async () => {\n expect(await getThemeProvider()).toBeNull();\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Higher-level wrapper for the host's entropy derivation (RFC-0007).\n *\n * `truApi.entropy.derive` takes a hex `context` and returns a hex `entropy`\n * payload wrapped in a neverthrow `ResultAsync`. `deriveEntropy` keeps the\n * ergonomic `Uint8Array → Result<Uint8Array, HostError>` signature: it\n * hex-encodes the context on the way in and decodes the entropy on the way out.\n *\n * @module\n */\n\nimport { createLogger } from \"@parity/product-sdk-logger\";\n\nimport { type HostError, HostUnavailableError } from \"./errors.js\";\nimport { type Result, err } from \"./result.js\";\nimport { fromHex, getTruApi, mapHostResult, toHex } from \"./truapi.js\";\n\nconst log = createLogger(\"host:entropy\");\n\n/**\n * Derive deterministic entropy from a context key (RFC-0007).\n *\n * The host derives entropy from the user's wallet + the provided context\n * key. Calling with the same key on the same wallet yields the same bytes;\n * different keys (or different wallets) yield uncorrelated entropy.\n *\n * @param key - Context key bytes (typically a SCALE-encoded discriminator).\n * @returns `ok` with the derived entropy bytes, or\n * `err(HostUnavailableError | HostCallFailedError)`.\n *\n * @example\n * ```ts\n * import { deriveEntropy } from \"@parity/product-sdk-host\";\n *\n * const r = await deriveEntropy(new TextEncoder().encode(\"my-app:seed-v1\"));\n * if (r.ok) { const seed = r.value; }\n * ```\n */\nexport async function deriveEntropy(key: Uint8Array): Promise<Result<Uint8Array, HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n return err(new HostUnavailableError(\"deriveEntropy: TruAPI unavailable\"));\n }\n log.debug(\"deriveEntropy\", { keyLen: key.length });\n\n return mapHostResult(\n truApi.entropy.derive({ context: toHex(key) }),\n (response) => fromHex(response.entropy),\n \"deriveEntropy failed\",\n );\n}\n\nif (import.meta.vitest) {\n const { test, expect, describe, vi } = import.meta.vitest;\n\n function okAsync<T>(value: T) {\n return { match: async (onOk: (v: T) => unknown) => onOk(value) };\n }\n\n async function withMockedTruApi<T>(\n client: unknown,\n fn: (mod: typeof import(\"./entropy.js\")) => Promise<T>,\n ): Promise<T> {\n vi.resetModules();\n vi.doMock(\"./truapi.js\", async (importOriginal) => {\n const original = await importOriginal<typeof import(\"./truapi.js\")>();\n return { ...original, getTruApi: async () => client };\n });\n try {\n const mod = await import(\"./entropy.js\");\n return await fn(mod);\n } finally {\n vi.doUnmock(\"./truapi.js\");\n vi.resetModules();\n }\n }\n\n // Tests live inside `describe` so the re-import in `withMockedTruApi`\n // (via `vi.resetModules`) doesn't re-register top-level `test()` calls.\n describe(\"deriveEntropy\", () => {\n test(\"returns err(HostUnavailableError) when TruAPI is unavailable\", async () => {\n await withMockedTruApi(null, async (mod) => {\n const result = await mod.deriveEntropy(new Uint8Array([1, 2, 3]));\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostUnavailableError\");\n }\n });\n });\n\n test(\"hex-encodes the context and decodes the entropy bytes\", async () => {\n const derive = vi.fn(() => okAsync({ entropy: \"0xc0ffee\" }));\n await withMockedTruApi({ entropy: { derive } }, async (mod) => {\n const result = await mod.deriveEntropy(new Uint8Array([0xab, 0xcd]));\n expect(derive).toHaveBeenCalledWith({ context: \"0xabcd\" });\n expect(result.ok).toBe(true);\n if (result.ok) {\n expect(Array.from(result.value)).toEqual([0xc0, 0xff, 0xee]);\n }\n });\n });\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Wrapper for the host's chat surface, backed by `truApi.chat.*`.\n *\n * `getChatManager()` returns a manager for room/bot registration, message\n * sending, and subscription to the room list and incoming actions.\n *\n * @module\n */\n\nimport type {\n ChatBotRegistrationStatus,\n ChatRoomRegistrationStatus,\n HostChatActionSubscribeItem,\n HostChatCreateRoomRequest,\n HostChatRegisterBotRequest,\n TrUApiClient,\n} from \"@parity/truapi\";\n\nimport { getClient, subscribeWithInterrupt } from \"./transport.js\";\nimport { unwrapHostResult } from \"./truapi.js\";\nimport type { HostSubscription } from \"./types.js\";\n\n/** Chat message payload variants and room metadata. Re-exported from `@parity/truapi`. */\nexport type { ChatMessageContent, ChatRoom } from \"@parity/truapi\";\nimport type { ChatMessageContent, ChatRoom } from \"@parity/truapi\";\n\n/** Action received via {@link ChatManager.subscribeAction} (`{ roomId, peer, payload }`). Re-exported from `@parity/truapi`. */\nexport type ChatReceivedAction = HostChatActionSubscribeItem;\n\n/** Result of registering a chat room (`\"New\" | \"Exists\"`). Re-exported from `@parity/truapi`. */\nexport type ChatRoomRegistrationResult = ChatRoomRegistrationStatus;\n\n/** Result of registering a bot (`\"New\" | \"Exists\"`). Re-exported from `@parity/truapi`. */\nexport type ChatBotRegistrationResult = ChatBotRegistrationStatus;\n\n/**\n * Chat manager handle. Exposes room/bot registration, message sending, and\n * subscription to the room list and incoming actions.\n */\nexport interface ChatManager {\n registerRoom(request: HostChatCreateRoomRequest): Promise<ChatRoomRegistrationResult>;\n registerBot(request: HostChatRegisterBotRequest): Promise<ChatBotRegistrationResult>;\n sendMessage(roomId: string, payload: ChatMessageContent): Promise<{ messageId: string }>;\n subscribeChatList(callback: (rooms: ChatRoom[]) => void): HostSubscription;\n subscribeAction(callback: (action: ChatReceivedAction) => void): HostSubscription;\n}\n\n/** Build a {@link ChatManager} over a TruAPI client's `chat` domain. */\nfunction adaptChatManager(client: TrUApiClient): ChatManager {\n const chat = client.chat;\n // Cache registration status by id so repeat calls don't re-prompt the host.\n const roomStatus = new Map<string, ChatRoomRegistrationResult>();\n const botStatus = new Map<string, ChatBotRegistrationResult>();\n\n return {\n async registerRoom(request) {\n const cached = roomStatus.get(request.roomId);\n if (cached) return cached;\n const response = await unwrapHostResult(\n chat.createRoom(request),\n \"chat registerRoom failed\",\n );\n roomStatus.set(request.roomId, response.status);\n return response.status;\n },\n async registerBot(request) {\n const cached = botStatus.get(request.botId);\n if (cached) return cached;\n const response = await unwrapHostResult(\n chat.registerBot(request),\n \"chat registerBot failed\",\n );\n botStatus.set(request.botId, response.status);\n return response.status;\n },\n async sendMessage(roomId, payload) {\n const response = await unwrapHostResult(\n chat.postMessage({ roomId, payload }),\n \"chat sendMessage failed\",\n );\n return { messageId: response.messageId };\n },\n subscribeChatList(callback) {\n return subscribeWithInterrupt(chat.listSubscribe(), (item) => callback(item.rooms));\n },\n subscribeAction(callback) {\n return subscribeWithInterrupt(chat.actionSubscribe(), callback);\n },\n };\n}\n\n/**\n * Get the host chat manager, backed by `truApi.chat.*`. Returns `null` when\n * running outside a host container.\n *\n * @returns The chat manager, or `null` if unavailable.\n *\n * @example\n * ```ts\n * import { getChatManager } from \"@parity/product-sdk-host\";\n *\n * const chat = await getChatManager();\n * if (chat) {\n * await chat.registerBot({ botId: \"echo\", name: \"Echo Bot\", icon: \"\" });\n * chat.subscribeAction((action) => { ... });\n * }\n * ```\n */\nexport async function getChatManager(): Promise<ChatManager | null> {\n const client = await getClient();\n return client ? adaptChatManager(client) : null;\n}\n\nif (import.meta.vitest) {\n const { test, expect } = import.meta.vitest;\n\n test(\"getChatManager returns null outside a container\", async () => {\n expect(await getChatManager()).toBeNull();\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Wrapper for the host's payment manager (RFC-0006), backed by\n * `truApi.payment.*`.\n *\n * Exposes balance subscription, top-up, payment requests, and payment-status\n * subscription. The flow is distinct from the CoinPayment / merchant-payments\n * surface (RFC-0017) — RFC-0006 is the user-initiated balance / top-up /\n * payment-request flow — but both operate on the same CoinPayment purses,\n * hence the shared `CoinPaymentPurseId` (omitted = the main purse).\n *\n * @module\n */\n\nimport type {\n Balance,\n CoinPaymentPurseId,\n HexString,\n HostPaymentBalanceSubscribeItem,\n HostPaymentStatusSubscribeItem,\n PaymentTopUpSource,\n TrUApiClient,\n} from \"@parity/truapi\";\n\nimport { getClient, subscribeWithInterrupt } from \"./transport.js\";\nimport { unwrapHostResult } from \"./truapi.js\";\nimport type { HostSubscription } from \"./types.js\";\n\n/**\n * Payment manager handle. Exposes balance subscription, top-up, payment\n * requests, and payment-status subscription.\n *\n * The balance / status / top-up-source shapes are `@parity/truapi`'s\n * `HostPaymentBalanceSubscribeItem`, `HostPaymentStatusSubscribeItem`, and\n * `PaymentTopUpSource` — used directly rather than re-aliased.\n */\nexport interface PaymentManager {\n subscribeBalance(\n callback: (balance: HostPaymentBalanceSubscribeItem) => void,\n purse?: CoinPaymentPurseId,\n ): HostSubscription;\n topUp(amount: Balance, source: PaymentTopUpSource, into?: CoinPaymentPurseId): Promise<void>;\n requestPayment(\n amount: Balance,\n destination: HexString,\n from?: CoinPaymentPurseId,\n ): Promise<{ id: string }>;\n subscribePaymentStatus(\n paymentId: string,\n callback: (status: HostPaymentStatusSubscribeItem) => void,\n ): HostSubscription;\n}\n\n/** Build a {@link PaymentManager} over a TruAPI client's `payment` domain. */\nfunction adaptPaymentManager(client: TrUApiClient): PaymentManager {\n const payment = client.payment;\n return {\n subscribeBalance(callback, purse) {\n return subscribeWithInterrupt(\n payment.balanceSubscribe({ request: { purse } }),\n callback,\n );\n },\n topUp(amount, source, into) {\n return unwrapHostResult(\n payment.topUp({ into, amount, source }),\n \"payment topUp failed\",\n );\n },\n async requestPayment(amount, destination, from) {\n const response = await unwrapHostResult(\n payment.request({ from, amount, destination }),\n \"payment requestPayment failed\",\n );\n return { id: response.id };\n },\n subscribePaymentStatus(paymentId, callback) {\n return subscribeWithInterrupt(\n payment.statusSubscribe({ request: { paymentId } }),\n callback,\n );\n },\n };\n}\n\n/**\n * Get the host payment manager, backed by `truApi.payment.*`. Returns `null`\n * when running outside a host container.\n *\n * @returns The payment manager, or `null` if unavailable.\n *\n * @example\n * ```ts\n * import { getPaymentManager } from \"@parity/product-sdk-host\";\n *\n * const payments = await getPaymentManager();\n * if (payments) {\n * const sub = payments.subscribeBalance((b) => { ... });\n * await payments.topUp(1_000_000n, { tag: \"ProductAccount\", value: { derivationIndex: { tag: \"Index\", value: 0 } } });\n * const { id } = await payments.requestPayment(500n, \"0x…\");\n * sub.unsubscribe();\n * }\n * ```\n */\nexport async function getPaymentManager(): Promise<PaymentManager | null> {\n const client = await getClient();\n return client ? adaptPaymentManager(client) : null;\n}\n\nif (import.meta.vitest) {\n const { test, expect } = import.meta.vitest;\n\n test(\"getPaymentManager returns null outside a container\", async () => {\n expect(await getPaymentManager()).toBeNull();\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Wrapper for the host's scheduled push-notification surface (RFC-0019),\n * backed by `truApi.notifications.*`.\n *\n * `getNotificationManager()` returns a handle exposing `push(input)` (resolves\n * to a {@link NotificationId}) and `cancel(id)`, matching the singleton\n * pattern already used by {@link getPaymentManager}, {@link getPreimageManager},\n * and {@link getHostLocalStorage}.\n *\n * @module\n */\n\nimport type { HostPushNotificationRequest, NotificationId, TrUApiClient } from \"@parity/truapi\";\n\nimport { getClient } from \"./transport.js\";\nimport { unwrapHostResult } from \"./truapi.js\";\n\n/**\n * Error variants the host raises when scheduling a push notification.\n *\n * A `{ tag }` tagged union re-exported from `@parity/truapi`:\n * `{ tag: \"ScheduleLimitReached\" }` (the host-wide pending-notification cap) or\n * `{ tag: \"Unknown\"; value: { reason } }`. {@link NotificationManager.push} /\n * {@link NotificationManager.cancel} reject with an `Error` whose `cause`\n * carries this value, so branch on it — e.g.\n * `(err as Error).cause?.tag === \"ScheduleLimitReached\"`.\n */\nexport type { HostPushNotificationError as PushNotificationError } from \"@parity/truapi\";\n\n/**\n * Host-assigned id for a scheduled notification — pass to\n * {@link NotificationManager.cancel}. Re-exported from `@parity/truapi`.\n */\nexport type { NotificationId };\n\n/**\n * Push payload: `text`, an optional `deeplink`, and an optional `scheduledAt`\n * (Unix timestamp in milliseconds; omit for immediate delivery). Re-exported\n * from the truapi wire request type so the shape stays in lockstep with the\n * protocol.\n */\nexport type PushNotificationInput = HostPushNotificationRequest;\n\n/**\n * Host notification manager handle. Exposes `push(input)` (resolves to a\n * {@link NotificationId}) and `cancel(id)`.\n */\nexport interface NotificationManager {\n push(input: PushNotificationInput): Promise<NotificationId>;\n cancel(id: NotificationId): Promise<void>;\n}\n\n/** Build a {@link NotificationManager} over a TruAPI client's `notifications` domain. */\nfunction adaptNotificationManager(client: TrUApiClient): NotificationManager {\n const notifications = client.notifications;\n return {\n async push(input) {\n const response = await unwrapHostResult(\n notifications.sendPushNotification(input),\n \"notification push failed\",\n );\n return response.id;\n },\n async cancel(id) {\n await unwrapHostResult(\n notifications.cancelPushNotification({ id }),\n \"notification cancel failed\",\n );\n },\n };\n}\n\n/**\n * Get the host notification manager, backed by `truApi.notifications.*`.\n * Returns `null` when running outside a host container.\n *\n * @returns The notification manager, or `null` if unavailable.\n *\n * @example\n * ```ts\n * import { getNotificationManager, type PushNotificationError } from \"@parity/product-sdk-host\";\n *\n * const notifications = await getNotificationManager();\n * if (notifications) {\n * try {\n * const id = await notifications.push({\n * text: \"Doors open in 1h\",\n * scheduledAt: someUnixMs,\n * });\n * // later: await notifications.cancel(id);\n * } catch (err) {\n * const cause = (err as Error).cause as PushNotificationError | undefined;\n * if (cause?.tag === \"ScheduleLimitReached\") {\n * // host hit its pending-notification cap — surface to the user\n * }\n * }\n * }\n * ```\n */\nexport async function getNotificationManager(): Promise<NotificationManager | null> {\n const client = await getClient();\n return client ? adaptNotificationManager(client) : null;\n}\n\nif (import.meta.vitest) {\n const { test, expect } = import.meta.vitest;\n\n test(\"getNotificationManager returns null outside a container\", async () => {\n expect(await getNotificationManager()).toBeNull();\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Higher-level wrapper for the host's deep-link navigation.\n *\n * `truApi.system.navigateTo` returns a neverthrow `ResultAsync`; consumers\n * still have to unwrap it themselves. {@link navigateTo} collapses that to a\n * `Result<void, HostError>`-returning Promise.\n *\n * @module\n */\n\nimport { createLogger } from \"@parity/product-sdk-logger\";\n\nimport { type HostError, HostUnavailableError } from \"./errors.js\";\nimport { type Result, err } from \"./result.js\";\nimport { getTruApi, mapHostResult } from \"./truapi.js\";\n\nconst log = createLogger(\"host:navigation\");\n\n/**\n * Ask the host to navigate to a URL (deep link or external link).\n *\n * Calls `truApi.system.navigateTo` and unwraps the response. The host resolves\n * the destination itself — a `dot`-suffixed deep link (e.g.\n * `\"https://search.dot\"`) routes to another app/route inside the container, an\n * `https://` URL opens externally.\n *\n * @param url - The URL to navigate to.\n * @returns `ok` on success, or `err`: {@link HostUnavailableError} if the host\n * is unavailable, or {@link HostCallFailedError} if it denies the navigation\n * (`NavigateToErr::PermissionDenied`) or fails otherwise (`NavigateToErr::Unknown`).\n *\n * @example\n * ```ts\n * import { navigateTo } from \"@parity/product-sdk-host\";\n *\n * const r = await navigateTo(\"https://search.dot\");\n * if (!r.ok) handle(r.error);\n * ```\n */\nexport async function navigateTo(url: string): Promise<Result<void, HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n return err(new HostUnavailableError(\"navigateTo: TruAPI unavailable\"));\n }\n log.debug(\"navigateTo\", { url });\n\n return mapHostResult(truApi.system.navigateTo({ url }), () => undefined, \"navigateTo failed\");\n}\n\nif (import.meta.vitest) {\n const { test, expect, describe, vi } = import.meta.vitest;\n\n async function withMockedTruApi<T>(\n bridge: { system?: { navigateTo?: (req: unknown) => unknown } } | null,\n fn: (mod: typeof import(\"./navigation.js\")) => Promise<T>,\n ): Promise<T> {\n vi.resetModules();\n vi.doMock(\"./truapi.js\", async (importOriginal) => {\n const original = await importOriginal<typeof import(\"./truapi.js\")>();\n return {\n ...original,\n getTruApi: async () => bridge,\n };\n });\n try {\n const mod = await import(\"./navigation.js\");\n return await fn(mod);\n } finally {\n vi.doUnmock(\"./truapi.js\");\n vi.resetModules();\n }\n }\n\n describe(\"navigateTo\", () => {\n test(\"returns err(HostUnavailableError) when TruAPI is unavailable\", async () => {\n await withMockedTruApi(null, async (mod) => {\n const result = await mod.navigateTo(\"https://search.dot\");\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostUnavailableError\");\n }\n });\n });\n\n test(\"returns ok on success\", async () => {\n await withMockedTruApi(\n {\n system: {\n navigateTo: vi.fn().mockReturnValue({\n match: async (onOk: (v: unknown) => unknown) => onOk(undefined),\n }),\n },\n },\n async (mod) => {\n expect(await mod.navigateTo(\"https://search.dot\")).toEqual({\n ok: true,\n value: undefined,\n });\n },\n );\n });\n\n test(\"wraps host errors in err(HostCallFailedError) with a diagnostic message\", async () => {\n await withMockedTruApi(\n {\n system: {\n navigateTo: vi.fn().mockReturnValue({\n match: async (\n _onOk: (v: unknown) => unknown,\n onErr: (e: unknown) => unknown,\n ) => onErr({ tag: \"PermissionDenied\" }),\n }),\n },\n },\n async (mod) => {\n const result = await mod.navigateTo(\"https://search.dot\");\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostCallFailedError\");\n expect(result.error.message).toMatch(/navigateTo failed: PermissionDenied/);\n }\n },\n );\n });\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Higher-level wrappers for the host's feature-support probe.\n *\n * `truApi.system.featureSupported` returns a neverthrow `ResultAsync`;\n * {@link featureSupported} collapses that to a `Result` carrying the host's\n * boolean answer. {@link isChainSupported} is a convenience over the only\n * feature variant the host exposes today (`Chain`).\n *\n * @module\n */\n\nimport { createLogger } from \"@parity/product-sdk-logger\";\n\nimport { type HostError, HostUnavailableError } from \"./errors.js\";\nimport { type Result, err } from \"./result.js\";\nimport { getTruApi, type HexString, mapHostResult } from \"./truapi.js\";\n\nconst log = createLogger(\"host:features\");\n\n/**\n * A feature the host can be probed for via {@link featureSupported}.\n *\n * The only variant today is `Chain`, carrying the chain's `0x`-prefixed genesis\n * hash. This is a flattened form of truapi's `HostFeatureSupportedRequest`,\n * which nests the hash as `{ tag: \"Chain\"; value: { genesisHash } }` — we\n * inline `value` as the `HexString` for ergonomics and re-nest it at the call\n * site. New variants surface here as a widening of the union.\n */\nexport type Feature = { tag: \"Chain\"; value: HexString };\n\n/**\n * Probe the host for support of a specific feature.\n *\n * Calls `truApi.system.featureSupported`, unwraps the response, and returns the\n * host's boolean answer.\n *\n * @param feature - The feature to probe for.\n * @returns `ok(true)` if the host supports the feature, `ok(false)` otherwise,\n * or `err(HostUnavailableError | HostCallFailedError)`.\n *\n * @example\n * ```ts\n * import { featureSupported } from \"@parity/product-sdk-host\";\n *\n * const r = await featureSupported({ tag: \"Chain\", value: genesisHash });\n * if (r.ok && r.value) { ... }\n * ```\n */\nexport async function featureSupported(feature: Feature): Promise<Result<boolean, HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n return err(new HostUnavailableError(\"featureSupported: TruAPI unavailable\"));\n }\n log.debug(\"featureSupported\", { tag: feature.tag });\n\n return mapHostResult(\n truApi.system.featureSupported({ tag: feature.tag, value: { genesisHash: feature.value } }),\n (response) => response.supported,\n \"featureSupported failed\",\n );\n}\n\n/**\n * Convenience probe: is the chain with the given genesis hash supported by the\n * host? Wraps {@link featureSupported} for the `Chain` feature variant.\n *\n * @param genesisHash - The chain's `0x`-prefixed genesis hash.\n * @returns `ok(true)` if the host supports the chain, `ok(false)` otherwise, or\n * `err(HostUnavailableError | HostCallFailedError)`.\n *\n * @example\n * ```ts\n * import { isChainSupported } from \"@parity/product-sdk-host\";\n *\n * const r = await isChainSupported(genesisHash);\n * if (!r.ok || !r.value) {\n * tellUserChainUnavailable();\n * }\n * ```\n */\nexport async function isChainSupported(\n genesisHash: HexString,\n): Promise<Result<boolean, HostError>> {\n return featureSupported({ tag: \"Chain\", value: genesisHash });\n}\n\nif (import.meta.vitest) {\n const { test, expect, describe, vi } = import.meta.vitest;\n\n async function withMockedTruApi<T>(\n bridge: { system?: { featureSupported?: (req: unknown) => unknown } } | null,\n fn: (mod: typeof import(\"./features.js\")) => Promise<T>,\n ): Promise<T> {\n vi.resetModules();\n vi.doMock(\"./truapi.js\", async (importOriginal) => {\n const original = await importOriginal<typeof import(\"./truapi.js\")>();\n return {\n ...original,\n getTruApi: async () => bridge,\n };\n });\n try {\n const mod = await import(\"./features.js\");\n return await fn(mod);\n } finally {\n vi.doUnmock(\"./truapi.js\");\n vi.resetModules();\n }\n }\n\n const okBridge = (supported: boolean) => ({\n system: {\n featureSupported: vi.fn().mockReturnValue({\n match: async (onOk: (v: unknown) => unknown) => onOk({ supported }),\n }),\n },\n });\n\n describe(\"featureSupported\", () => {\n test(\"returns err(HostUnavailableError) when TruAPI is unavailable\", async () => {\n await withMockedTruApi(null, async (mod) => {\n const result = await mod.featureSupported({ tag: \"Chain\", value: \"0x00\" });\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostUnavailableError\");\n }\n });\n });\n\n test(\"returns ok with the boolean outcome\", async () => {\n await withMockedTruApi(okBridge(true), async (mod) => {\n expect(await mod.featureSupported({ tag: \"Chain\", value: \"0x00\" })).toEqual({\n ok: true,\n value: true,\n });\n });\n });\n\n test(\"wraps host errors in err(HostCallFailedError) with a diagnostic message\", async () => {\n await withMockedTruApi(\n {\n system: {\n featureSupported: vi.fn().mockReturnValue({\n match: async (\n _onOk: (v: unknown) => unknown,\n onErr: (e: unknown) => unknown,\n ) => onErr({ reason: \"boom\" }),\n }),\n },\n },\n async (mod) => {\n const result = await mod.featureSupported({ tag: \"Chain\", value: \"0x00\" });\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostCallFailedError\");\n expect(result.error.message).toMatch(/featureSupported failed: boom/);\n }\n },\n );\n });\n });\n\n describe(\"isChainSupported\", () => {\n test(\"delegates to featureSupported with the Chain variant\", async () => {\n await withMockedTruApi(okBridge(false), async (mod) => {\n expect(await mod.isChainSupported(\"0x1234\")).toEqual({ ok: true, value: false });\n });\n });\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Higher-level wrapper for the host's chain-spec lookups.\n *\n * The host exposes three separate chain-spec calls — `chain.getSpecGenesisHash`,\n * `chain.getSpecChainName`, and `chain.getSpecProperties` — each reachable via\n * {@link getTruApi} and each returning a neverthrow `ResultAsync`.\n * {@link getChainSpec} fetches all three in one call and returns a single\n * struct so callers read whichever field they need, matching the JSON-RPC\n * `chainSpec_v1_*` family they mirror.\n *\n * @module\n */\n\nimport { createLogger } from \"@parity/product-sdk-logger\";\n\nimport type { HostError } from \"./errors.js\";\nimport { type Result, ok } from \"./result.js\";\nimport { getTruApi, type HexString, mapHostResult } from \"./truapi.js\";\n\nconst log = createLogger(\"host:chain-spec\");\n\n/**\n * Chain SS58/token properties as reported by the host's\n * `chainSpecProperties` call.\n *\n * The host returns this as a JSON string (mirroring the substrate\n * `chainSpec_v1_properties` JSON-RPC, whose payload is an open-ended object).\n * {@link getChainSpec} parses it into {@link ChainSpec.properties} and also\n * surfaces the untouched JSON as {@link ChainSpec.propertiesRaw}. The well-known substrate fields are\n * typed for convenience; the index signature keeps any chain-specific extras\n * reachable without `any` at the call site.\n */\nexport interface ChainProperties {\n /** Address prefix used for SS58 encoding (e.g. `0` for Polkadot). */\n ss58Format?: number;\n /** Decimal places of the chain's native token(s). */\n tokenDecimals?: number | number[];\n /** Ticker symbol(s) of the chain's native token(s). */\n tokenSymbol?: string | string[];\n /** Chain-specific extras passed through verbatim from the JSON payload. */\n [key: string]: unknown;\n}\n\n/**\n * Combined chain-spec view returned by {@link getChainSpec}.\n */\nexport interface ChainSpec {\n /** The chain's `0x`-prefixed genesis hash, as reported by the host. */\n genesisHash: HexString;\n /** Human-readable chain name (e.g. `\"Polkadot\"`). */\n name: string;\n /**\n * Parsed chain properties, or `null` if the host's JSON payload couldn't\n * be parsed. Inspect {@link propertiesRaw} for the original string.\n */\n properties: ChainProperties | null;\n /** The untouched JSON string the host returned for properties. */\n propertiesRaw: string;\n}\n\n/**\n * Fetch a chain's full spec (genesis hash, name, and properties) from the host\n * in one call.\n *\n * Issues the three underlying `chain.getSpec*` requests concurrently, unwraps\n * each response, and parses the properties JSON. Note the `genesisHash` in the\n * result is the value the host echoes back from `getSpecGenesisHash` for the\n * looked-up chain — pass the chain's known genesis hash as the lookup key.\n *\n * `null` (outside a container) is preserved as an `ok` value — it is an\n * expected state, not a failure — so callers branch on `r.ok && r.value`. A\n * real host-call failure surfaces on the `err` channel.\n *\n * @param genesisHash - The `0x`-prefixed genesis hash identifying the chain.\n * @returns `ok(spec)` with the combined {@link ChainSpec}, `ok(null)` if the\n * host is unavailable (running outside a container), or\n * `err(HostCallFailedError)` if any underlying host call fails.\n *\n * @example\n * ```ts\n * import { getChainSpec } from \"@parity/product-sdk-host\";\n *\n * const r = await getChainSpec(genesisHash);\n * if (r.ok && r.value) {\n * console.log(r.value.name, r.value.properties?.tokenSymbol);\n * }\n * ```\n */\nexport async function getChainSpec(\n genesisHash: HexString,\n): Promise<Result<ChainSpec | null, HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n log.debug(\"getChainSpec: TruAPI unavailable\");\n return ok(null);\n }\n log.debug(\"getChainSpec\", { genesisHash });\n\n const [genesisHashResult, nameResult, propertiesResult] = await Promise.all([\n mapHostResult(\n truApi.chain.getSpecGenesisHash({ genesisHash }),\n (response) => response.genesisHash,\n \"getChainSpec (genesisHash) failed\",\n ),\n mapHostResult(\n truApi.chain.getSpecChainName({ genesisHash }),\n (response) => response.chainName,\n \"getChainSpec (chainName) failed\",\n ),\n mapHostResult(\n truApi.chain.getSpecProperties({ genesisHash }),\n (response) => response.properties,\n \"getChainSpec (properties) failed\",\n ),\n ]);\n\n // Short-circuit on the first failing call.\n if (!genesisHashResult.ok) return genesisHashResult;\n if (!nameResult.ok) return nameResult;\n if (!propertiesResult.ok) return propertiesResult;\n\n const propertiesRaw = propertiesResult.value;\n let properties: ChainProperties | null;\n try {\n properties = JSON.parse(propertiesRaw) as ChainProperties;\n } catch (parseError) {\n log.debug(\"getChainSpec: properties JSON parse failed\", parseError);\n properties = null;\n }\n\n return ok({\n genesisHash: genesisHashResult.value,\n name: nameResult.value,\n properties,\n propertiesRaw,\n });\n}\n\nif (import.meta.vitest) {\n const { test, expect, describe, vi } = import.meta.vitest;\n\n async function withMockedTruApi<T>(\n bridge: {\n chain?: {\n getSpecGenesisHash?: (req: unknown) => unknown;\n getSpecChainName?: (req: unknown) => unknown;\n getSpecProperties?: (req: unknown) => unknown;\n };\n } | null,\n fn: (mod: typeof import(\"./chain-spec.js\")) => Promise<T>,\n ): Promise<T> {\n vi.resetModules();\n vi.doMock(\"./truapi.js\", async (importOriginal) => {\n const original = await importOriginal<typeof import(\"./truapi.js\")>();\n return {\n ...original,\n getTruApi: async () => bridge,\n };\n });\n try {\n const mod = await import(\"./chain-spec.js\");\n return await fn(mod);\n } finally {\n vi.doUnmock(\"./truapi.js\");\n vi.resetModules();\n }\n }\n\n /** A resolved ResultAsync stub yielding the given response object. */\n const okAsync = (response: unknown) => ({\n match: async (onOk: (v: unknown) => unknown) => onOk(response),\n });\n\n describe(\"getChainSpec\", () => {\n test(\"returns ok(null) when TruAPI is unavailable\", async () => {\n await withMockedTruApi(null, async (mod) => {\n expect(await mod.getChainSpec(\"0x00\")).toEqual({ ok: true, value: null });\n });\n });\n\n test(\"combines the three calls and parses properties JSON\", async () => {\n await withMockedTruApi(\n {\n chain: {\n getSpecGenesisHash: vi\n .fn()\n .mockReturnValue(okAsync({ genesisHash: \"0xabcd\" })),\n getSpecChainName: vi\n .fn()\n .mockReturnValue(okAsync({ chainName: \"Polkadot\" })),\n getSpecProperties: vi.fn().mockReturnValue(\n okAsync({\n properties:\n '{\"ss58Format\":0,\"tokenDecimals\":10,\"tokenSymbol\":\"DOT\"}',\n }),\n ),\n },\n },\n async (mod) => {\n const result = await mod.getChainSpec(\"0xabcd\");\n expect(result).toEqual({\n ok: true,\n value: {\n genesisHash: \"0xabcd\",\n name: \"Polkadot\",\n properties: { ss58Format: 0, tokenDecimals: 10, tokenSymbol: \"DOT\" },\n propertiesRaw:\n '{\"ss58Format\":0,\"tokenDecimals\":10,\"tokenSymbol\":\"DOT\"}',\n },\n });\n },\n );\n });\n\n test(\"leaves properties null when the JSON is malformed\", async () => {\n await withMockedTruApi(\n {\n chain: {\n getSpecGenesisHash: vi\n .fn()\n .mockReturnValue(okAsync({ genesisHash: \"0xabcd\" })),\n getSpecChainName: vi\n .fn()\n .mockReturnValue(okAsync({ chainName: \"Polkadot\" })),\n getSpecProperties: vi\n .fn()\n .mockReturnValue(okAsync({ properties: \"not json\" })),\n },\n },\n async (mod) => {\n const result = await mod.getChainSpec(\"0xabcd\");\n expect(result.ok).toBe(true);\n if (result.ok) {\n expect(result.value?.properties).toBeNull();\n expect(result.value?.propertiesRaw).toBe(\"not json\");\n }\n },\n );\n });\n\n test(\"returns err(HostCallFailedError) when a host call fails\", async () => {\n await withMockedTruApi(\n {\n chain: {\n getSpecGenesisHash: vi.fn().mockReturnValue({\n match: async (\n _onOk: (v: unknown) => unknown,\n onErr: (e: unknown) => unknown,\n ) => onErr({ reason: \"boom\" }),\n }),\n getSpecChainName: vi\n .fn()\n .mockReturnValue(okAsync({ chainName: \"Polkadot\" })),\n getSpecProperties: vi.fn().mockReturnValue(okAsync({ properties: \"{}\" })),\n },\n },\n async (mod) => {\n const result = await mod.getChainSpec(\"0xabcd\");\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostCallFailedError\");\n expect(result.error.message).toMatch(\n /getChainSpec \\(genesisHash\\) failed: boom/,\n );\n }\n },\n );\n });\n });\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Higher-level wrappers for the host's transaction broadcast lifecycle.\n *\n * `truApi.chain.broadcastTransaction` / `truApi.chain.stopTransaction` are\n * reachable via {@link getTruApi}, but consumers have to unwrap the neverthrow\n * `ResultAsync` themselves. {@link broadcastTransaction} and\n * {@link stopTransaction} collapse that to `Result`-returning Promises, mirroring\n * the JSON-RPC `transaction_v1_broadcast` / `transaction_v1_stop` pair they\n * wrap.\n *\n * @module\n */\n\nimport { createLogger } from \"@parity/product-sdk-logger\";\n\nimport { type HostError, HostUnavailableError } from \"./errors.js\";\nimport { type Result, err } from \"./result.js\";\nimport { getTruApi, type HexString, mapHostResult } from \"./truapi.js\";\n\nconst log = createLogger(\"host:chain-transaction\");\n\n/**\n * Broadcast a signed transaction to the network via the host.\n *\n * Calls `truApi.chain.broadcastTransaction` and unwraps the response. The host\n * keeps re-broadcasting until the transaction is finalized/dropped or\n * {@link stopTransaction} is called with the returned operation id.\n *\n * @param genesisHash - The `0x`-prefixed genesis hash of the target chain.\n * @param transaction - The `0x`-prefixed SCALE-encoded signed transaction.\n * @returns `ok` with the operation id to pass to {@link stopTransaction} (or\n * `null` if the host accepted the broadcast without issuing one), or\n * `err(HostUnavailableError | HostCallFailedError)`.\n *\n * @example\n * ```ts\n * import { broadcastTransaction, stopTransaction } from \"@parity/product-sdk-host\";\n *\n * const r = await broadcastTransaction(genesisHash, signedTx);\n * // later, to stop re-broadcasting:\n * if (r.ok && r.value) await stopTransaction(genesisHash, r.value);\n * ```\n */\nexport async function broadcastTransaction(\n genesisHash: HexString,\n transaction: HexString,\n): Promise<Result<string | null, HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n return err(new HostUnavailableError(\"broadcastTransaction: TruAPI unavailable\"));\n }\n log.debug(\"broadcastTransaction\", { genesisHash });\n\n return mapHostResult(\n truApi.chain.broadcastTransaction({ genesisHash, transaction }),\n (response) => response.operationId ?? null,\n \"broadcastTransaction failed\",\n );\n}\n\n/**\n * Stop an in-flight broadcast started by {@link broadcastTransaction}.\n *\n * Calls `truApi.chain.stopTransaction` and unwraps the response.\n *\n * @param genesisHash - The `0x`-prefixed genesis hash of the target chain.\n * @param operationId - The operation id returned by\n * {@link broadcastTransaction}.\n * @returns `ok` on success, or `err(HostUnavailableError | HostCallFailedError)`.\n *\n * @example\n * ```ts\n * await stopTransaction(genesisHash, operationId);\n * ```\n */\nexport async function stopTransaction(\n genesisHash: HexString,\n operationId: string,\n): Promise<Result<void, HostError>> {\n const truApi = await getTruApi();\n if (!truApi) {\n return err(new HostUnavailableError(\"stopTransaction: TruAPI unavailable\"));\n }\n log.debug(\"stopTransaction\", { genesisHash, operationId });\n\n return mapHostResult(\n truApi.chain.stopTransaction({ genesisHash, operationId }),\n () => undefined,\n \"stopTransaction failed\",\n );\n}\n\nif (import.meta.vitest) {\n const { test, expect, describe, vi } = import.meta.vitest;\n\n async function withMockedTruApi<T>(\n bridge: {\n chain?: {\n broadcastTransaction?: (req: unknown) => unknown;\n stopTransaction?: (req: unknown) => unknown;\n };\n } | null,\n fn: (mod: typeof import(\"./chain-transaction.js\")) => Promise<T>,\n ): Promise<T> {\n vi.resetModules();\n vi.doMock(\"./truapi.js\", async (importOriginal) => {\n const original = await importOriginal<typeof import(\"./truapi.js\")>();\n return {\n ...original,\n getTruApi: async () => bridge,\n };\n });\n try {\n const mod = await import(\"./chain-transaction.js\");\n return await fn(mod);\n } finally {\n vi.doUnmock(\"./truapi.js\");\n vi.resetModules();\n }\n }\n\n /** A resolved ResultAsync stub yielding the given response object. */\n const ok = (response: unknown) => ({\n match: async (onOk: (v: unknown) => unknown) => onOk(response),\n });\n /** A rejected ResultAsync stub yielding a truapi `GenericError` (`{ reason }`). */\n const errResult = (reason: string) => ({\n match: async (_onOk: (v: unknown) => unknown, onErr: (e: unknown) => unknown) =>\n onErr({ reason }),\n });\n\n describe(\"broadcastTransaction\", () => {\n test(\"returns err(HostUnavailableError) when TruAPI is unavailable\", async () => {\n await withMockedTruApi(null, async (mod) => {\n const result = await mod.broadcastTransaction(\"0x00\", \"0x01\");\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostUnavailableError\");\n }\n });\n });\n\n test(\"returns ok with the operation id\", async () => {\n await withMockedTruApi(\n {\n chain: {\n broadcastTransaction: vi.fn().mockReturnValue(ok({ operationId: \"op-1\" })),\n },\n },\n async (mod) => {\n expect(await mod.broadcastTransaction(\"0x00\", \"0x01\")).toEqual({\n ok: true,\n value: \"op-1\",\n });\n },\n );\n });\n\n test(\"passes through a missing operation id as ok(null)\", async () => {\n await withMockedTruApi(\n {\n chain: {\n broadcastTransaction: vi.fn().mockReturnValue(ok({})),\n },\n },\n async (mod) => {\n expect(await mod.broadcastTransaction(\"0x00\", \"0x01\")).toEqual({\n ok: true,\n value: null,\n });\n },\n );\n });\n\n test(\"wraps host errors in err(HostCallFailedError) with a diagnostic message\", async () => {\n await withMockedTruApi(\n {\n chain: {\n broadcastTransaction: vi.fn().mockReturnValue(errResult(\"boom\")),\n },\n },\n async (mod) => {\n const result = await mod.broadcastTransaction(\"0x00\", \"0x01\");\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostCallFailedError\");\n expect(result.error.message).toMatch(/broadcastTransaction failed: boom/);\n }\n },\n );\n });\n });\n\n describe(\"stopTransaction\", () => {\n test(\"returns err(HostUnavailableError) when TruAPI is unavailable\", async () => {\n await withMockedTruApi(null, async (mod) => {\n const result = await mod.stopTransaction(\"0x00\", \"op-1\");\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostUnavailableError\");\n }\n });\n });\n\n test(\"returns ok on success\", async () => {\n await withMockedTruApi(\n {\n chain: {\n stopTransaction: vi.fn().mockReturnValue(ok(undefined)),\n },\n },\n async (mod) => {\n expect(await mod.stopTransaction(\"0x00\", \"op-1\")).toEqual({\n ok: true,\n value: undefined,\n });\n },\n );\n });\n\n test(\"wraps host errors in err(HostCallFailedError) with a diagnostic message\", async () => {\n await withMockedTruApi(\n {\n chain: {\n stopTransaction: vi.fn().mockReturnValue(errResult(\"boom\")),\n },\n },\n async (mod) => {\n const result = await mod.stopTransaction(\"0x00\", \"op-1\");\n expect(result.ok).toBe(false);\n if (!result.ok) {\n expect(result.error.name).toBe(\"HostCallFailedError\");\n expect(result.error.message).toMatch(/stopTransaction failed: boom/);\n }\n },\n );\n });\n });\n}\n"]}