@parity/product-sdk-host 0.13.0 → 0.14.1

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.
@@ -34,6 +34,7 @@ function subscribeWithInterrupt(observable, onNext) {
34
34
  complete: () => interruptCallback?.()
35
35
  });
36
36
  return {
37
+ subscriptionId: sub.subscriptionId,
37
38
  unsubscribe: () => sub.unsubscribe(),
38
39
  onInterrupt: (callback) => {
39
40
  interruptCallback = callback;
@@ -45,5 +46,5 @@ function subscribeWithInterrupt(observable, onNext) {
45
46
  }
46
47
 
47
48
  export { getClient, isCorrectEnvironment, setTruApiClient, subscribeWithInterrupt };
48
- //# sourceMappingURL=chunk-3SWF5CWC.js.map
49
- //# sourceMappingURL=chunk-3SWF5CWC.js.map
49
+ //# sourceMappingURL=chunk-GDXSV7JV.js.map
50
+ //# sourceMappingURL=chunk-GDXSV7JV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transport.ts"],"names":["sandboxGetClientSync","sandboxIsCorrectEnvironment"],"mappings":";;;AA8BA,IAAI,cAAA,GAAsC,IAAA;AAE1C,SAAS,iBAAA,GAA6B;AAClC,EAAA,IAAI;AAIA,IAAA,OAAO,OAAA,CAAQ,IAAI,QAAA,KAAa,YAAA;AAAA,EACpC,CAAA,CAAA,MAAQ;AAEJ,IAAA,OAAO,KAAA;AAAA,EACX;AACJ;AAYO,SAAS,gBAAgB,MAAA,EAAmC;AAC/D,EAAA,IAAI,MAAA,KAAW,IAAA,IAAQ,iBAAA,EAAkB,EAAG;AACxC,IAAA,OAAA,CAAQ,IAAA;AAAA,MACJ;AAAA,KACJ;AAAA,EACJ;AACA,EAAA,cAAA,GAAiB,MAAA;AACrB;AAMO,SAAS,aAAA,GAAqC;AACjD,EAAA,OAAO,kBAAkBA,eAAA,EAAqB;AAClD;AAMO,SAAS,oBAAA,GAAgC;AAC5C,EAAA,OAAO,cAAA,KAAmB,QAAQC,sBAAA,EAA4B;AAClE;AAMA,eAAsB,SAAA,GAA0C;AAC5D,EAAA,OAAO,aAAA,EAAc;AACzB;AAUO,SAAS,sBAAA,CACZ,YACA,MAAA,EACqB;AACrB,EAAA,IAAI,iBAAA;AACJ,EAAA,MAAM,GAAA,GAAM,WAAW,SAAA,CAAU;AAAA,IAC7B,IAAA,EAAM,MAAA;AAAA,IACN,KAAA,EAAO,CAAC,MAAA,KAAW,iBAAA,GAAoB,MAAM,CAAA;AAAA,IAC7C,QAAA,EAAU,MAAM,iBAAA;AAAoB,GACvC,CAAA;AACD,EAAA,OAAO;AAAA,IACH,gBAAgB,GAAA,CAAI,cAAA;AAAA,IACpB,WAAA,EAAa,MAAM,GAAA,CAAI,WAAA,EAAY;AAAA,IACnC,WAAA,EAAa,CAAC,QAAA,KAAa;AACvB,MAAA,iBAAA,GAAoB,QAAA;AACpB,MAAA,OAAO,MAAM;AACT,QAAA,IAAI,iBAAA,KAAsB,UAAU,iBAAA,GAAoB,MAAA;AAAA,MAC5D,CAAA;AAAA,IACJ;AAAA,GACJ;AACJ","file":"chunk-GDXSV7JV.js","sourcesContent":["// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Access to the in-house TruAPI client (`@parity/truapi`) for the host package.\n *\n * Environment detection and the lazily-built, cached client come from\n * `@parity/truapi/sandbox`; this module layers the product-sdk-specific glue on\n * top — an async {@link getClient} accessor and {@link subscribeWithInterrupt},\n * which adapts a truapi stream into the host's {@link HostSubscription} shape.\n *\n * @module\n */\n\nimport type { ObservableLike, TrUApiClient } from \"@parity/truapi\";\nimport {\n getClientSync as sandboxGetClientSync,\n isCorrectEnvironment as sandboxIsCorrectEnvironment,\n} from \"@parity/truapi/sandbox\";\n\nimport type { HostSubscription } from \"./types.js\";\n\n/** A {@link HostSubscription} carrying the transport-assigned subscription id. */\nexport interface TransportSubscription extends HostSubscription {\n readonly subscriptionId: string;\n}\n\n// Test-only override. When set — via `setTruApiClient`, exposed through\n// `@parity/product-sdk-host/testing` — every host accessor resolves this client\n// instead of the sandbox one. `null` in production, so the branches below are\n// no-ops there.\nlet clientOverride: TrUApiClient | null = null;\n\nfunction isProductionBuild(): boolean {\n try {\n // Must stay a plain `process.env.NODE_ENV` member expression: bundlers\n // (Vite, esbuild, webpack) substitute it textually, which is how this\n // check works in browser builds where `process` doesn't exist.\n return process.env.NODE_ENV === \"production\";\n } catch {\n // No `process` and no bundler define — can't tell, stay quiet.\n return false;\n }\n}\n\n/**\n * Test-only seam: force {@link getClient} / {@link getClientSync} to return\n * `client`, and {@link isCorrectEnvironment} to report `true`. Pass `null` to\n * restore normal detection. Exposed through `@parity/product-sdk-host/testing`,\n * not the package's main entry.\n *\n * Calling this in a production build silently reroutes every host accessor to\n * the injected client, so we warn — it almost always means a `/testing` import\n * leaked into a production path.\n */\nexport function setTruApiClient(client: TrUApiClient | null): void {\n if (client !== null && isProductionBuild()) {\n console.warn(\n \"[product-sdk] setTruApiClient() was called in a production build. This is a test-only seam from @parity/product-sdk-host/testing; a leaked import will silently reroute all host access to the injected client.\",\n );\n }\n clientOverride = client;\n}\n\n/**\n * Synchronous TruAPI client accessor. Returns the injected test client when one\n * is set, otherwise the sandbox client (`null` outside a host container).\n */\nexport function getClientSync(): TrUApiClient | null {\n return clientOverride ?? sandboxGetClientSync();\n}\n\n/**\n * Host-container detection. `true` when a test client is injected, otherwise the\n * sandbox heuristic (iframe / webview marker / injected message port).\n */\nexport function isCorrectEnvironment(): boolean {\n return clientOverride !== null || sandboxIsCorrectEnvironment();\n}\n\n/**\n * Get the TruAPI client. Returns `null` outside a host container. Async wrapper\n * over {@link getClientSync} for the host wrappers that already `await` it.\n */\nexport async function getClient(): Promise<TrUApiClient | null> {\n return getClientSync();\n}\n\n/**\n * Adapt a truapi `ObservableLike` stream into the host's callback-style\n * {@link HostSubscription} (`unsubscribe` + `onInterrupt`). `onNext` fires for\n * each item; the registered `onInterrupt` callback fires when the host ends the\n * subscription server-side — which the generated client surfaces as either\n * `complete` (a host interrupt frame) or `error` (transport close). Shared by\n * the statement-store and preimage adapters, which both expose this shape.\n */\nexport function subscribeWithInterrupt<Item, Reason = never>(\n observable: ObservableLike<Item, Reason>,\n onNext: (item: Item) => void,\n): TransportSubscription {\n let interruptCallback: ((reason?: unknown) => void) | undefined;\n const sub = observable.subscribe({\n next: onNext,\n error: (reason) => interruptCallback?.(reason),\n complete: () => interruptCallback?.(),\n });\n return {\n subscriptionId: sub.subscriptionId,\n unsubscribe: () => sub.unsubscribe(),\n onInterrupt: (callback) => {\n interruptCallback = callback;\n return () => {\n if (interruptCallback === callback) interruptCallback = undefined;\n };\n },\n };\n}\n\nif (import.meta.vitest) {\n const { test, expect, afterEach } = import.meta.vitest;\n\n afterEach(() => setTruApiClient(null));\n\n // Environment detection and client building are covered by `@parity/truapi`'s\n // own sandbox tests; here we only assert the local glue degrades outside a\n // host container.\n test(\"getClientSync returns null outside a container\", () => {\n expect(getClientSync()).toBeNull();\n });\n\n test(\"getClient resolves null outside a container\", async () => {\n expect(await getClient()).toBeNull();\n });\n\n test(\"setTruApiClient overrides the client and container detection\", async () => {\n const fake = {} as TrUApiClient;\n setTruApiClient(fake);\n expect(getClientSync()).toBe(fake);\n expect(await getClient()).toBe(fake);\n expect(isCorrectEnvironment()).toBe(true);\n\n setTruApiClient(null);\n expect(getClientSync()).toBeNull();\n expect(isCorrectEnvironment()).toBe(false);\n });\n\n test(\"setTruApiClient warns when injecting in a production build\", () => {\n const original = process.env.NODE_ENV;\n const warnings: string[] = [];\n const realWarn = console.warn;\n console.warn = (...args: unknown[]) => void warnings.push(String(args[0]));\n try {\n process.env.NODE_ENV = \"production\";\n setTruApiClient({} as TrUApiClient);\n expect(warnings).toHaveLength(1);\n expect(warnings[0]).toContain(\"production build\");\n\n // Clearing the override must not warn.\n setTruApiClient(null);\n expect(warnings).toHaveLength(1);\n } finally {\n console.warn = realWarn;\n process.env.NODE_ENV = original;\n }\n });\n\n test(\"subscribeWithInterrupt preserves the transport subscription id\", () => {\n const observable = {\n subscribe: () => ({\n subscriptionId: \"p:17\",\n unsubscribe: () => {},\n }),\n [Symbol.observable]() {\n return this;\n },\n } as ObservableLike<never>;\n\n const subscription = subscribeWithInterrupt(observable, () => {});\n\n expect(subscription.subscriptionId).toBe(\"p:17\");\n });\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { JsonRpcProvider, PolkadotSigner } from 'polkadot-api';
2
- import { Topic, RemoteStatementStoreSubscribeItem, Statement, StatementProof, SignedStatement, HexString, GenericError, TrUApiClient, AllocatableResource, AllocationOutcome, HostGetUserIdError, HostRequestLoginResponse, HostRequestLoginError, ProductAccountId, ProductAccount as ProductAccount$1, HostAccountGetError, HostAccountGetAliasResponse, LegacyAccount, RingLocation, HostAccountCreateProofError, HostAccountConnectionStatusSubscribeItem, HostDevicePermissionRequest, RemotePermission, HostThemeSubscribeItem, ChatBotRegistrationStatus, HostChatCreateRoomRequest, ChatRoomRegistrationStatus, HostChatRegisterBotRequest, ChatMessageContent, ChatRoom, HostChatActionSubscribeItem, HostPaymentBalanceSubscribeItem, PaymentPurseId, Balance, PaymentTopUpSource, HostPaymentStatusSubscribeItem, HostPushNotificationRequest, NotificationId } from '@parity/truapi';
3
- export { AllocatableResource, AllocationOutcome, ChatMessageContent, ChatRoom, HexString, HostPaymentBalanceSubscribeItem, HostPaymentStatusSubscribeItem, NotificationId, PaymentTopUpSource, ProductAccountId, HostPushNotificationError as PushNotificationError, RemotePermission, RingLocation, SignedStatement, Statement, StatementProof, ThemeName, ThemeVariant, Topic } from '@parity/truapi';
2
+ import { Topic, RemoteStatementStoreSubscribeItem, Statement, StatementProof, SignedStatement, HexString, scale, TrUApiClient, AllocatableResource, AllocationOutcome, VersionedHostGetUserIdError, HostRequestLoginResponse, VersionedHostRequestLoginError, ProductAccountId, ProductAccount as ProductAccount$1, VersionedHostAccountGetError, ProductProofContext, RingLocation, ContextualAlias as ContextualAlias$1, VersionedHostAccountGetAliasError, LegacyAccount, VersionedHostGetLegacyAccountsError, HostAccountCreateProofResponse, VersionedHostAccountCreateProofError, HostAccountConnectionStatusSubscribeItem, HostDevicePermissionRequest, RemotePermission, HostThemeSubscribeItem, ChatBotRegistrationStatus, HostChatCreateRoomRequest, ChatRoomRegistrationStatus, HostChatRegisterBotRequest, ChatMessageContent, ChatRoom, HostChatActionSubscribeItem, HostPaymentBalanceSubscribeItem, CoinPaymentPurseId, Balance, PaymentTopUpSource, HostPaymentStatusSubscribeItem, HostPushNotificationRequest, NotificationId } from '@parity/truapi';
3
+ export { AllocatableResource, AllocationOutcome, ChatMessageContent, ChatRoom, HexString, HostPaymentBalanceSubscribeItem, HostPaymentStatusSubscribeItem, NotificationId, PaymentTopUpSource, ProductAccountId, ProductProofContext, HostPushNotificationError as PushNotificationError, RemotePermission, RingLocation, SignedStatement, Statement, StatementProof, ThemeName, ThemeVariant, Topic } from '@parity/truapi';
4
4
  import { SdkError } from '@parity/product-sdk-errors';
5
5
  export { SdkError, isSdkError } from '@parity/product-sdk-errors';
6
6
  import { Result } from '@parity/result';
@@ -156,13 +156,12 @@ declare function getStatementStore(): Promise<HostStatementStore | null>;
156
156
  * chain-specific endpoints used by multiple packages.
157
157
  */
158
158
  /**
159
- * Bulletin Chain RPC endpoints per network environment. `paseo` (Paseo Next v2),
160
- * `summit`, and `devnet` (public Paseo testnet) are populated today; `polkadot`
161
- * and `kusama` are reserved for when those Bulletin deployments go live.
159
+ * Bulletin Chain RPC endpoints per network environment. `paseo` (Paseo Next v2)
160
+ * and `devnet` (public Paseo testnet) are populated today; `polkadot` and
161
+ * `kusama` are reserved for when those Bulletin deployments go live.
162
162
  */
163
163
  declare const BULLETIN_RPCS: {
164
164
  readonly paseo: readonly ["wss://paseo-bulletin-next-rpc.polkadot.io"];
165
- readonly summit: readonly ["wss://summit-bulletin-rpc.polkadot.io"];
166
165
  readonly devnet: readonly ["wss://bulletin-paseo.tservices.es:8443"];
167
166
  readonly polkadot: string[];
168
167
  readonly kusama: string[];
@@ -189,34 +188,25 @@ declare const DEFAULT_BULLETIN_ENDPOINT: string;
189
188
  */
190
189
 
191
190
  /**
192
- * The structured error payload `@parity/truapi` surfaces on the `Err` channel of
193
- * a host call, once unwrapped from the versioned wire envelope. Every host error
194
- * union is built from these:
195
- *
196
- * - the catch-all {@link GenericError} (`{ reason }`),
197
- * - a unit tagged variant (`{ tag }`), or
198
- * - a tagged variant carrying a reason (`{ tag, value: { reason } }`).
199
- *
200
- * `GenericError` is imported from `@parity/truapi`; the `{ tag }` members are a
201
- * deliberate widening of truapi's per-domain named variants (the formatter is
202
- * tag-agnostic). truapi has no umbrella error union to import today — once it
203
- * exports a canonical tagged-error union from codegen, replace these local
204
- * members with that import so the type is protocol-sourced rather than
205
- * hand-widened.
206
- *
207
- * This is the *payload* the host public API carries inside a
208
- * {@link HostCallFailedError} on the `err` channel of its `Result` returns — not
209
- * the error type consumers branch on.
191
+ * What a `Domain`-tagged call error carries. Widened from truapi's per-domain
192
+ * `Versioned*Error` types (all `{ tag: "V1", value: <domain error> }` today)
193
+ * so one payload type covers every call.
210
194
  */
211
- type HostErrorPayload = GenericError | {
212
- tag: string;
213
- value?: undefined;
214
- } | {
195
+ type VersionedDomainError = {
215
196
  tag: string;
216
- value: {
217
- reason: string;
218
- };
197
+ value?: unknown;
219
198
  };
199
+ /**
200
+ * The error a host call puts on its `Err` channel — truapi's canonical
201
+ * {@link scale.CallErrorValue} envelope. `Denied` / `Unsupported` /
202
+ * `MalformedFrame` / `HostFailure` are transport-level failures; `Domain`
203
+ * wraps the actual per-domain error in a versioned envelope, which
204
+ * {@link formatHostError} digs through when rendering.
205
+ *
206
+ * This is the payload {@link HostCallFailedError} carries — not the error
207
+ * type consumers branch on.
208
+ */
209
+ type HostErrorPayload = scale.CallErrorValue<VersionedDomainError>;
220
210
  /**
221
211
  * Extract a human-readable message from a host-side error.
222
212
  *
@@ -426,10 +416,24 @@ type ProductAccount = ProductAccountId & Omit<ProductAccount$1, "publicKey"> & {
426
416
  *
427
417
  * Proves account membership in a ring without revealing which account.
428
418
  *
429
- * Derived from `@parity/truapi`'s alias response, with both fields decoded to bytes.
419
+ * Derived from `@parity/truapi`'s `ContextualAlias`, with both fields decoded to bytes.
430
420
  */
431
421
  type ContextualAlias = {
432
- [K in keyof HostAccountGetAliasResponse]: Uint8Array;
422
+ [K in keyof ContextualAlias$1]: Uint8Array;
423
+ };
424
+ /**
425
+ * A Ring VRF proof plus the values needed to verify it downstream (e.g.
426
+ * against a precompile): the alias it commits to, and the ring member index /
427
+ * revision the proof was generated against.
428
+ *
429
+ * Derived from `@parity/truapi`'s `HostAccountCreateProofResponse`, with the
430
+ * byte fields decoded.
431
+ */
432
+ type RingVRFProof = Omit<HostAccountCreateProofResponse, "proof" | "contextualAlias"> & {
433
+ /** Raw ring VRF proof bytes. */
434
+ proof: Uint8Array;
435
+ /** Alias derived for the request's context. */
436
+ contextualAlias: ContextualAlias;
433
437
  };
434
438
  /**
435
439
  * Accounts provider handle, backed by `truApi.account.*` / `truApi.signing.*`.
@@ -437,17 +441,28 @@ type ContextualAlias = {
437
441
  * user identity, connection status, and `PolkadotSigner` factories.
438
442
  *
439
443
  * Lookup methods return a neverthrow `ResultAsync` (use `.match(ok, err)`);
440
- * the signer factories return a synchronous PAPI `PolkadotSigner`.
444
+ * the signer factories return a synchronous PAPI `PolkadotSigner`. The `err`
445
+ * channel carries truapi's canonical `CallErrorValue` envelope around the
446
+ * per-call versioned domain error, exactly as the generated client returns it.
441
447
  */
442
448
  interface AccountsProvider {
443
449
  getUserId(): ResultAsync$1<{
444
450
  primaryUsername: string;
445
- }, HostGetUserIdError>;
446
- requestLogin(reason?: string): ResultAsync$1<HostRequestLoginResponse, HostRequestLoginError>;
447
- getProductAccount(dotNsIdentifier: string, derivationIndex?: number): ResultAsync$1<ProductAccount, HostAccountGetError>;
448
- getProductAccountAlias(dotNsIdentifier: string, derivationIndex?: number): ResultAsync$1<ContextualAlias, HostAccountGetError>;
449
- getLegacyAccounts(): ResultAsync$1<HostAccount[], HostAccountGetError>;
450
- createRingVRFProof(dotNsIdentifier: string, derivationIndex: number, location: RingLocation, message: Uint8Array): ResultAsync$1<Uint8Array, HostAccountCreateProofError>;
451
+ }, scale.CallErrorValue<VersionedHostGetUserIdError>>;
452
+ requestLogin(reason?: string): ResultAsync$1<HostRequestLoginResponse, scale.CallErrorValue<VersionedHostRequestLoginError>>;
453
+ getProductAccount(dotNsIdentifier: string, derivationIndex?: number): ResultAsync$1<ProductAccount, scale.CallErrorValue<VersionedHostAccountGetError>>;
454
+ /**
455
+ * Derive the contextual alias for a proof context and ring. The host
456
+ * selects the member key within the ring no per-account addressing.
457
+ */
458
+ getProductAccountAlias(context: ProductProofContext, location: RingLocation): ResultAsync$1<ContextualAlias, scale.CallErrorValue<VersionedHostAccountGetAliasError>>;
459
+ getLegacyAccounts(): ResultAsync$1<HostAccount[], scale.CallErrorValue<VersionedHostGetLegacyAccountsError>>;
460
+ /**
461
+ * Generate a Ring VRF proof binding `message` to the product-scoped
462
+ * `context`. The host selects the member key within the ring; the result
463
+ * carries the proof plus its verification values ({@link RingVRFProof}).
464
+ */
465
+ createRingVRFProof(context: ProductProofContext, location: RingLocation, message: Uint8Array): ResultAsync$1<RingVRFProof, scale.CallErrorValue<VersionedHostAccountCreateProofError>>;
451
466
  /**
452
467
  * Build a `PolkadotSigner` for a product account. Signing routes through the
453
468
  * host's `createTransaction` path: the host decodes the metadata and forwards
@@ -669,9 +684,10 @@ declare function getChatManager(): Promise<ChatManager | null>;
669
684
  * `truApi.payment.*`.
670
685
  *
671
686
  * Exposes balance subscription, top-up, payment requests, and payment-status
672
- * subscription. Distinct from the CoinPayment / merchant-payments surface
673
- * (RFC-0017): RFC-0006 is the user-initiated balance / top-up / payment-request
674
- * flow.
687
+ * subscription. The flow is distinct from the CoinPayment / merchant-payments
688
+ * surface (RFC-0017) RFC-0006 is the user-initiated balance / top-up /
689
+ * payment-request flow — but both operate on the same CoinPayment purses,
690
+ * hence the shared `CoinPaymentPurseId` (omitted = the main purse).
675
691
  *
676
692
  * @module
677
693
  */
@@ -685,9 +701,9 @@ declare function getChatManager(): Promise<ChatManager | null>;
685
701
  * `PaymentTopUpSource` — used directly rather than re-aliased.
686
702
  */
687
703
  interface PaymentManager {
688
- subscribeBalance(callback: (balance: HostPaymentBalanceSubscribeItem) => void, purse?: PaymentPurseId): HostSubscription;
689
- topUp(amount: Balance, source: PaymentTopUpSource, into?: PaymentPurseId): Promise<void>;
690
- requestPayment(amount: Balance, destination: HexString, from?: PaymentPurseId): Promise<{
704
+ subscribeBalance(callback: (balance: HostPaymentBalanceSubscribeItem) => void, purse?: CoinPaymentPurseId): HostSubscription;
705
+ topUp(amount: Balance, source: PaymentTopUpSource, into?: CoinPaymentPurseId): Promise<void>;
706
+ requestPayment(amount: Balance, destination: HexString, from?: CoinPaymentPurseId): Promise<{
691
707
  id: string;
692
708
  }>;
693
709
  subscribePaymentStatus(paymentId: string, callback: (status: HostPaymentStatusSubscribeItem) => void): HostSubscription;
@@ -998,4 +1014,4 @@ declare function broadcastTransaction(genesisHash: HexString, transaction: HexSt
998
1014
  */
999
1015
  declare function stopTransaction(genesisHash: HexString, operationId: string): Promise<Result<void, HostError>>;
1000
1016
 
1001
- export { type AccountsProvider, BULLETIN_RPCS, ChainNotSupportedError, type ChainProperties, type ChainSpec, type ChatBotRegistrationResult, type ChatManager, type ChatReceivedAction, type ChatRoomRegistrationResult, type ContextualAlias, DEFAULT_BULLETIN_ENDPOINT, type DevicePermissionKind, type Feature, type HostAccount, HostCallFailedError, HostError, type HostErrorPayload, type HostLocalStorage, type HostStatementStore, type HostSubscription, HostUnavailableError, type NotificationManager, type PaymentManager, type PreimageManager, type ProductAccount, type PushNotificationInput, type RemotePermissionItem, type ResultAsync, type StatementTopicFilter, type StatementsPage, type ThemeMode, type ThemeProvider, type TruApi, broadcastTransaction, createHostLocalStorage, createHostPreimageManager, createProofAuthorized, deriveEntropy, featureSupported, formatHostError, fromHex, getAccountsProvider, getChainSpec, getChatManager, getHostLocalStorage, getHostProvider, getNotificationManager, getPaymentManager, getPreimageManager, getStatementStore, getThemeProvider, getTruApi, isChainSupported, isHostError, isInsideContainer, navigateTo, requestDevicePermission, requestPermission, requestResourceAllocation, stopTransaction, toHex };
1017
+ export { type AccountsProvider, BULLETIN_RPCS, ChainNotSupportedError, type ChainProperties, type ChainSpec, type ChatBotRegistrationResult, type ChatManager, type ChatReceivedAction, type ChatRoomRegistrationResult, type ContextualAlias, DEFAULT_BULLETIN_ENDPOINT, type DevicePermissionKind, type Feature, type HostAccount, HostCallFailedError, HostError, type HostErrorPayload, type HostLocalStorage, type HostStatementStore, type HostSubscription, HostUnavailableError, type NotificationManager, type PaymentManager, type PreimageManager, type ProductAccount, type PushNotificationInput, type RemotePermissionItem, type ResultAsync, type RingVRFProof, type StatementTopicFilter, type StatementsPage, type ThemeMode, type ThemeProvider, type TruApi, broadcastTransaction, createHostLocalStorage, createHostPreimageManager, createProofAuthorized, deriveEntropy, featureSupported, formatHostError, fromHex, getAccountsProvider, getChainSpec, getChatManager, getHostLocalStorage, getHostProvider, getNotificationManager, getPaymentManager, getPreimageManager, getStatementStore, getThemeProvider, getTruApi, isChainSupported, isHostError, isInsideContainer, navigateTo, requestDevicePermission, requestPermission, requestResourceAllocation, stopTransaction, toHex };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { getClient, isCorrectEnvironment, subscribeWithInterrupt } from './chunk-3SWF5CWC.js';
2
- export { isCorrectEnvironment as isInsideContainerSync } from './chunk-3SWF5CWC.js';
1
+ import { getClient, isCorrectEnvironment, subscribeWithInterrupt } from './chunk-GDXSV7JV.js';
2
+ export { isCorrectEnvironment as isInsideContainerSync } from './chunk-GDXSV7JV.js';
3
3
  import { createLogger } from '@parity/product-sdk-logger';
4
4
  import { scale } from '@parity/truapi';
5
5
  import { err, ok } from '@parity/result';
@@ -9,21 +9,25 @@ import { unifyMetadata, decAnyMetadata } from '@polkadot-api/substrate-bindings'
9
9
  import { AccountId } from 'polkadot-api';
10
10
 
11
11
  // src/errors.ts
12
- function isHostErrorPayload(error) {
13
- if (error == null || typeof error !== "object") return false;
14
- const obj = error;
15
- return typeof obj.reason === "string" || typeof obj.tag === "string";
12
+ function isTagged(value) {
13
+ return value != null && typeof value === "object" && typeof value.tag === "string";
14
+ }
15
+ function hasReason(value) {
16
+ return value != null && typeof value === "object" && typeof value.reason === "string";
16
17
  }
17
18
  function formatHostError(error) {
18
19
  if (error instanceof Error) return error.message;
19
20
  if (typeof error === "string") return error;
20
- if (isHostErrorPayload(error)) {
21
- if ("tag" in error) {
22
- if (error.value != null && typeof error.value.reason === "string") {
23
- return `${error.tag}: ${error.value.reason}`;
24
- }
25
- return error.tag;
21
+ if (isTagged(error)) {
22
+ if (error.tag === "Domain" && isTagged(error.value) && error.value.value !== void 0) {
23
+ return formatHostError(error.value.value);
24
+ }
25
+ if (hasReason(error.value)) {
26
+ return `${error.tag}: ${error.value.reason}`;
26
27
  }
28
+ return error.tag;
29
+ }
30
+ if (hasReason(error)) {
27
31
  return error.reason;
28
32
  }
29
33
  if (error != null && typeof error === "object" && "message" in error) {
@@ -170,8 +174,6 @@ function createHostPapiProvider(client, genesisHash) {
170
174
  return (onMessage) => {
171
175
  const activeFollows = /* @__PURE__ */ new Map();
172
176
  const activeBroadcasts = /* @__PURE__ */ new Set();
173
- let nextSubId = 0;
174
- const getNextSubId = () => `follow_${nextSubId++}`;
175
177
  function sendJsonRpcResponse(id, result) {
176
178
  onMessage({ jsonrpc: "2.0", id, result });
177
179
  }
@@ -192,24 +194,45 @@ function createHostPapiProvider(client, genesisHash) {
192
194
  switch (method) {
193
195
  case "chainHead_v1_follow": {
194
196
  const [withRuntime] = params;
195
- const syntheticSubId = getNextSubId();
196
197
  const ref = {};
198
+ const pendingItems = [];
199
+ const forwardItem = (followSubscriptionId2, item) => {
200
+ if (item.tag === "Stop" && activeFollows.delete(followSubscriptionId2)) {
201
+ ref.handle?.unsubscribe();
202
+ }
203
+ sendFollowEvent(followSubscriptionId2, convertFollowEventToJsonRpc(item));
204
+ };
197
205
  ref.handle = subscribeWithInterrupt(
198
206
  chain.followHeadSubscribe({ request: { genesisHash, withRuntime } }),
199
207
  (item) => {
200
- if (item.tag === "Stop" && activeFollows.delete(syntheticSubId)) {
201
- ref.handle?.unsubscribe();
208
+ const followSubscriptionId2 = ref.handle?.subscriptionId;
209
+ if (!followSubscriptionId2) {
210
+ pendingItems.push(item);
211
+ return;
202
212
  }
203
- sendFollowEvent(syntheticSubId, convertFollowEventToJsonRpc(item));
213
+ forwardItem(followSubscriptionId2, item);
204
214
  }
205
215
  );
216
+ const followSubscriptionId = ref.handle.subscriptionId;
217
+ if (!followSubscriptionId) {
218
+ ref.handle.unsubscribe();
219
+ sendJsonRpcError(
220
+ id,
221
+ JSON_RPC_INTERNAL_ERROR,
222
+ "Host follow subscription did not start"
223
+ );
224
+ break;
225
+ }
206
226
  ref.handle.onInterrupt(() => {
207
- if (activeFollows.delete(syntheticSubId)) {
208
- sendFollowEvent(syntheticSubId, { event: "stop" });
227
+ if (activeFollows.delete(followSubscriptionId)) {
228
+ sendFollowEvent(followSubscriptionId, { event: "stop" });
209
229
  }
210
230
  });
211
- activeFollows.set(syntheticSubId, ref.handle);
212
- sendJsonRpcResponse(id, syntheticSubId);
231
+ activeFollows.set(followSubscriptionId, ref.handle);
232
+ sendJsonRpcResponse(id, followSubscriptionId);
233
+ for (const item of pendingItems) {
234
+ forwardItem(followSubscriptionId, item);
235
+ }
213
236
  break;
214
237
  }
215
238
  case "chainHead_v1_unfollow": {
@@ -552,7 +575,6 @@ async function getStatementStore() {
552
575
  // src/chains.ts
553
576
  var BULLETIN_RPCS = {
554
577
  paseo: ["wss://paseo-bulletin-next-rpc.polkadot.io"],
555
- summit: ["wss://summit-bulletin-rpc.polkadot.io"],
556
578
  devnet: ["wss://bulletin-paseo.tservices.es:8443"],
557
579
  polkadot: [],
558
580
  kusama: []
@@ -593,8 +615,8 @@ function adaptAccountsProvider(client) {
593
615
  derivationIndex
594
616
  }));
595
617
  },
596
- getProductAccountAlias(dotNsIdentifier, derivationIndex = 0) {
597
- return account.getAccountAlias({ productAccountId: { dotNsIdentifier, derivationIndex } }).map((response) => ({
618
+ getProductAccountAlias(context, location) {
619
+ return account.getAccountAlias({ context, ringLocation: location }).map((response) => ({
598
620
  context: fromHex(response.context),
599
621
  alias: fromHex(response.alias)
600
622
  }));
@@ -607,12 +629,20 @@ function adaptAccountsProvider(client) {
607
629
  }))
608
630
  );
609
631
  },
610
- createRingVRFProof(dotNsIdentifier, derivationIndex, location, message) {
632
+ createRingVRFProof(context, location, message) {
611
633
  return account.createAccountProof({
612
- productAccountId: { dotNsIdentifier, derivationIndex },
634
+ context,
613
635
  ringLocation: location,
614
- context: toHex(message)
615
- }).map((response) => fromHex(response.proof));
636
+ message: toHex(message)
637
+ }).map((response) => ({
638
+ proof: fromHex(response.proof),
639
+ contextualAlias: {
640
+ context: fromHex(response.contextualAlias.context),
641
+ alias: fromHex(response.contextualAlias.alias)
642
+ },
643
+ ringIndex: response.ringIndex,
644
+ ringRevision: response.ringRevision
645
+ }));
616
646
  },
617
647
  getProductAccountSigner(account_) {
618
648
  const productAccountId = {