@parity/product-sdk-chain-client 0.1.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.
package/src/clients.ts ADDED
@@ -0,0 +1,346 @@
1
+ import type { ChainDefinition, PolkadotClient } from "polkadot-api";
2
+ import { createClient } from "polkadot-api";
3
+ import { createProvider } from "./providers.js";
4
+ import { getClientCache, clearClientCache } from "./hmr.js";
5
+ import type { ChainEntry, ChainClientConfig, ChainClient } from "./types.js";
6
+
7
+ // Cache keys are scoped by a fingerprint of the config so that two
8
+ // `createChainClient` calls with different chain sets don't collide.
9
+ const cacheKey = (fingerprint: string, genesis: string) => `${fingerprint}:${genesis}`;
10
+
11
+ function findEntryByGenesis(genesis: string): ChainEntry | undefined {
12
+ for (const [key, entry] of getClientCache()) {
13
+ if (key.endsWith(`:${genesis}`)) return entry;
14
+ }
15
+ }
16
+
17
+ const clientInstances = new Map<string, Promise<ChainClient<any>>>();
18
+
19
+ /** Build a stable fingerprint from sorted chain names + genesis hashes. */
20
+ function configFingerprint(chains: Record<string, ChainDefinition>): string {
21
+ return Object.entries(chains)
22
+ .sort(([a], [b]) => a.localeCompare(b))
23
+ .map(([name, desc]) => `${name}:${desc.genesis ?? "unknown"}`)
24
+ .join("|");
25
+ }
26
+
27
+ /**
28
+ * Create a multi-chain client with user-provided descriptors and RPC endpoints.
29
+ *
30
+ * Returns fully-typed APIs for each chain plus raw `PolkadotClient` access via `.raw`.
31
+ * Connections use host routing (via `@parity/product-sdk-host`) when inside a container,
32
+ * falling back to direct WebSocket RPC.
33
+ *
34
+ * Results are cached by genesis-hash fingerprint — calling with the same descriptors
35
+ * returns the same instance.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import { createChainClient } from "@parity/product-sdk-chain-client";
40
+ * import { paseo_asset_hub } from "./descriptors/paseo-asset-hub";
41
+ * import { bulletin } from "./descriptors/bulletin";
42
+ *
43
+ * const client = await createChainClient({
44
+ * chains: { assetHub: paseo_asset_hub, bulletin },
45
+ * rpcs: {
46
+ * assetHub: ["wss://sys.ibp.network/asset-hub-paseo"],
47
+ * bulletin: ["wss://paseo-bulletin-rpc.polkadot.io"],
48
+ * },
49
+ * });
50
+ *
51
+ * // Fully typed from your descriptors
52
+ * const account = await client.assetHub.query.System.Account.getValue(addr);
53
+ * const fee = await client.bulletin.query.TransactionStorage.ByteFee.getValue();
54
+ *
55
+ * // Raw client for advanced use (e.g., InkSdk for contracts)
56
+ * import { createInkSdk } from "@polkadot-api/sdk-ink";
57
+ * const inkSdk = createInkSdk(client.raw.assetHub, { atBest: true });
58
+ *
59
+ * // Cleanup
60
+ * client.destroy();
61
+ * ```
62
+ */
63
+ export async function createChainClient<const TChains extends Record<string, ChainDefinition>>(
64
+ config: ChainClientConfig<TChains>,
65
+ ): Promise<ChainClient<TChains>> {
66
+ const fingerprint = configFingerprint(config.chains);
67
+
68
+ const existing = clientInstances.get(fingerprint);
69
+ if (existing) return existing as Promise<ChainClient<TChains>>;
70
+
71
+ const promise = initChainClient(config, fingerprint).catch((err) => {
72
+ // Clean up any clients created before the failure to avoid leaking
73
+ // WebSocket connections that are unreachable except via destroyAll().
74
+ const cache = getClientCache();
75
+ for (const [key, entry] of cache) {
76
+ if (key.startsWith(`${fingerprint}:`)) {
77
+ try {
78
+ entry.client.destroy();
79
+ } catch {
80
+ /* already destroyed */
81
+ }
82
+ cache.delete(key);
83
+ }
84
+ }
85
+ clientInstances.delete(fingerprint);
86
+ throw err;
87
+ });
88
+ clientInstances.set(fingerprint, promise);
89
+ return promise;
90
+ }
91
+
92
+ /* @integration */
93
+ async function initChainClient<const TChains extends Record<string, ChainDefinition>>(
94
+ config: ChainClientConfig<TChains>,
95
+ fingerprint: string,
96
+ ): Promise<ChainClient<TChains>> {
97
+ const names = Object.keys(config.chains) as (string & keyof TChains)[];
98
+ const clientCache = getClientCache();
99
+
100
+ // Create providers and clients in parallel
101
+ const entries = await Promise.all(
102
+ names.map(async (name) => {
103
+ const descriptor = config.chains[name] as ChainDefinition;
104
+ const genesis = descriptor.genesis;
105
+ if (!genesis) {
106
+ throw new Error(`Descriptor for chain "${name}" has no genesis hash.`);
107
+ }
108
+ const provider = await createProvider(genesis);
109
+ const client = createClient(provider);
110
+
111
+ // Populate HMR cache so getClient() and isConnected() work
112
+ const key = cacheKey(fingerprint, genesis);
113
+ if (!clientCache.has(key)) {
114
+ clientCache.set(key, {
115
+ client,
116
+ api: new Map(),
117
+ } satisfies ChainEntry);
118
+ }
119
+
120
+ return { name, descriptor, client, genesis };
121
+ }),
122
+ );
123
+
124
+ // Build typed APIs and raw client map
125
+ const apis = {} as Record<string, unknown>;
126
+ const raw = {} as Record<string, PolkadotClient>;
127
+
128
+ for (const { name, descriptor, client } of entries) {
129
+ apis[name] = client.getTypedApi(descriptor);
130
+ raw[name] = client;
131
+ }
132
+
133
+ return {
134
+ ...apis,
135
+ raw,
136
+ destroy() {
137
+ for (const { genesis } of entries) {
138
+ const key = cacheKey(fingerprint, genesis);
139
+ const entry = clientCache.get(key);
140
+ if (entry) {
141
+ try {
142
+ entry.client.destroy();
143
+ } catch {
144
+ /* already destroyed */
145
+ }
146
+ clientCache.delete(key);
147
+ }
148
+ }
149
+ clientInstances.delete(fingerprint);
150
+ },
151
+ } as ChainClient<TChains>;
152
+ }
153
+
154
+ /**
155
+ * Destroy all chain client instances and reset internal caches.
156
+ *
157
+ * Tears down every connection created by {@link createChainClient}.
158
+ */
159
+ export function destroyAll(): void {
160
+ clearClientCache();
161
+ clientInstances.clear();
162
+ }
163
+
164
+ /**
165
+ * Get the raw `PolkadotClient` for a connected chain by its descriptor.
166
+ *
167
+ * The chain must have been initialized via {@link createChainClient} first.
168
+ * Alternatively, use `client.raw.<name>` on the returned {@link ChainClient}.
169
+ *
170
+ * @throws If the chain has not been connected yet.
171
+ */
172
+ export function getClient(descriptor: ChainDefinition): PolkadotClient {
173
+ const genesis = descriptor.genesis;
174
+ if (!genesis) throw new Error("Descriptor has no genesis hash.");
175
+ const entry = findEntryByGenesis(genesis);
176
+ if (!entry?.client) {
177
+ throw new Error(
178
+ `Chain not connected (genesis: ${genesis}). Call createChainClient() first to establish connections.`,
179
+ );
180
+ }
181
+ return entry.client;
182
+ }
183
+
184
+ /**
185
+ * Check if a chain is currently connected.
186
+ *
187
+ * Synchronous — no side effects, no initialization.
188
+ */
189
+ export function isConnected(descriptor: ChainDefinition): boolean {
190
+ const genesis = descriptor.genesis;
191
+ if (!genesis) return false;
192
+ return findEntryByGenesis(genesis) !== undefined;
193
+ }
194
+
195
+ if (import.meta.vitest) {
196
+ const { test, expect, beforeEach } = import.meta.vitest;
197
+
198
+ const fakeDescriptor = { genesis: "0xtest" } as ChainDefinition;
199
+ const fakeClient = {
200
+ destroy: () => {},
201
+ getTypedApi: () => ({}),
202
+ } as unknown as PolkadotClient;
203
+
204
+ function seedCache(genesis: string, client: PolkadotClient, fp = "test") {
205
+ getClientCache().set(cacheKey(fp, genesis), {
206
+ client,
207
+ api: new Map(),
208
+ });
209
+ }
210
+
211
+ beforeEach(() => {
212
+ clearClientCache();
213
+ clientInstances.clear();
214
+ });
215
+
216
+ // --- isConnected ---
217
+
218
+ test("isConnected returns false for unknown chain", () => {
219
+ expect(isConnected(fakeDescriptor)).toBe(false);
220
+ });
221
+
222
+ test("isConnected returns true after cache is populated", () => {
223
+ seedCache("0xtest", fakeClient);
224
+ expect(isConnected(fakeDescriptor)).toBe(true);
225
+ });
226
+
227
+ test("isConnected returns false for descriptor without genesis", () => {
228
+ expect(isConnected({} as ChainDefinition)).toBe(false);
229
+ });
230
+
231
+ // --- getClient ---
232
+
233
+ test("getClient returns client from cache", () => {
234
+ seedCache("0xtest", fakeClient);
235
+ expect(getClient(fakeDescriptor)).toBe(fakeClient);
236
+ });
237
+
238
+ test("getClient throws for unconnected chain", () => {
239
+ expect(() => getClient(fakeDescriptor)).toThrow(/Chain not connected/);
240
+ });
241
+
242
+ test("getClient throws for descriptor without genesis", () => {
243
+ expect(() => getClient({} as ChainDefinition)).toThrow(/no genesis hash/);
244
+ });
245
+
246
+ // --- destroyAll ---
247
+
248
+ test("destroyAll calls client.destroy() and clears caches", () => {
249
+ let destroyed = false;
250
+ const trackableClient = {
251
+ destroy: () => {
252
+ destroyed = true;
253
+ },
254
+ getTypedApi: () => ({}),
255
+ } as unknown as PolkadotClient;
256
+ seedCache("0xtest", trackableClient);
257
+ clientInstances.set("test", Promise.resolve({} as ChainClient<any>));
258
+ destroyAll();
259
+ expect(destroyed).toBe(true);
260
+ expect(isConnected(fakeDescriptor)).toBe(false);
261
+ expect(clientInstances.size).toBe(0);
262
+ });
263
+
264
+ // --- createChainClient ---
265
+
266
+ test("createChainClient returns same promise for identical config", async () => {
267
+ const fakeResult = {} as ChainClient<any>;
268
+ const fp = configFingerprint({ a: fakeDescriptor });
269
+ clientInstances.set(fp, Promise.resolve(fakeResult));
270
+ const result = await createChainClient({
271
+ chains: { a: fakeDescriptor },
272
+ rpcs: { a: [] },
273
+ });
274
+ expect(result).toBe(fakeResult);
275
+ });
276
+
277
+ test("createChainClient deduplicates concurrent calls", async () => {
278
+ const fakeResult = {} as ChainClient<any>;
279
+ const fp = configFingerprint({ x: fakeDescriptor });
280
+ clientInstances.set(fp, Promise.resolve(fakeResult));
281
+ const [a, b] = await Promise.all([
282
+ createChainClient({ chains: { x: fakeDescriptor }, rpcs: { x: [] } }),
283
+ createChainClient({ chains: { x: fakeDescriptor }, rpcs: { x: [] } }),
284
+ ]);
285
+ expect(a).toBe(b);
286
+ });
287
+
288
+ test("createChainClient returns different results for different configs", async () => {
289
+ const descA = { genesis: "0xaaa" } as ChainDefinition;
290
+ const descB = { genesis: "0xbbb" } as ChainDefinition;
291
+ const resultA = {} as ChainClient<any>;
292
+ const resultB = {} as ChainClient<any>;
293
+ clientInstances.set(configFingerprint({ a: descA }), Promise.resolve(resultA));
294
+ clientInstances.set(configFingerprint({ b: descB }), Promise.resolve(resultB));
295
+ const a = await createChainClient({ chains: { a: descA }, rpcs: { a: [] } });
296
+ const b = await createChainClient({ chains: { b: descB }, rpcs: { b: [] } });
297
+ expect(a).not.toBe(b);
298
+ });
299
+
300
+ // --- configFingerprint ---
301
+
302
+ test("configFingerprint is stable regardless of key order", () => {
303
+ const d1 = { genesis: "0x1" } as ChainDefinition;
304
+ const d2 = { genesis: "0x2" } as ChainDefinition;
305
+ expect(configFingerprint({ a: d1, b: d2 })).toBe(configFingerprint({ b: d2, a: d1 }));
306
+ });
307
+
308
+ // --- findEntryByGenesis ---
309
+
310
+ test("findEntryByGenesis returns undefined for missing genesis", () => {
311
+ expect(findEntryByGenesis("0xnonexistent")).toBeUndefined();
312
+ });
313
+
314
+ // --- full lifecycle ---
315
+
316
+ test("full lifecycle: seed, verify connected, destroy, verify disconnected", () => {
317
+ seedCache("0xtest", fakeClient);
318
+ expect(isConnected(fakeDescriptor)).toBe(true);
319
+ expect(getClient(fakeDescriptor)).toBe(fakeClient);
320
+ destroyAll();
321
+ expect(isConnected(fakeDescriptor)).toBe(false);
322
+ expect(() => getClient(fakeDescriptor)).toThrow(/Chain not connected/);
323
+ });
324
+
325
+ test("two fingerprints cached independently, destroy one leaves other intact", () => {
326
+ const sharedGenesis = "0xshared";
327
+ const clientA = { destroy: () => {} } as PolkadotClient;
328
+ const clientB = { destroy: () => {} } as PolkadotClient;
329
+ const descriptorShared = { genesis: sharedGenesis } as ChainDefinition;
330
+
331
+ seedCache(sharedGenesis, clientA, "fpA");
332
+ seedCache(sharedGenesis, clientB, "fpB");
333
+
334
+ expect(isConnected(descriptorShared)).toBe(true);
335
+
336
+ // Destroy only fpA's entry
337
+ const cache = getClientCache();
338
+ const keyA = cacheKey("fpA", sharedGenesis);
339
+ cache.get(keyA)?.client.destroy();
340
+ cache.delete(keyA);
341
+
342
+ // fpB's entry still alive
343
+ expect(isConnected(descriptorShared)).toBe(true);
344
+ expect(getClient(descriptorShared)).toBe(clientB);
345
+ });
346
+ }
package/src/hmr.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { ChainEntry } from "./types.js";
2
+
3
+ declare global {
4
+ var __chainClientCache: Map<string, ChainEntry> | undefined;
5
+ }
6
+
7
+ /** Get the HMR-safe client cache, keyed by genesis hash. */
8
+ export function getClientCache(): Map<string, ChainEntry> {
9
+ globalThis.__chainClientCache ??= new Map();
10
+ return globalThis.__chainClientCache;
11
+ }
12
+
13
+ /** Clear all entries from the client cache. Destroys active clients. */
14
+ export function clearClientCache(): void {
15
+ const cache = getClientCache();
16
+ for (const entry of cache.values()) {
17
+ try {
18
+ entry.client.destroy();
19
+ } catch {
20
+ // client may already be destroyed
21
+ }
22
+ }
23
+ cache.clear();
24
+ }
25
+
26
+ if (import.meta.vitest) {
27
+ const { test, expect } = import.meta.vitest;
28
+
29
+ test("getClientCache returns a Map", () => {
30
+ const cache = getClientCache();
31
+ expect(cache).toBeInstanceOf(Map);
32
+ });
33
+
34
+ test("getClientCache returns the same instance on repeated calls", () => {
35
+ const a = getClientCache();
36
+ const b = getClientCache();
37
+ expect(a).toBe(b);
38
+ });
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ // Core BYOD API — zero descriptor overhead
2
+ export { createChainClient, destroyAll, getClient, isConnected } from "./clients.js";
3
+
4
+ // Preset environments — zero-config path with built-in descriptors
5
+ export { getChainAPI } from "./presets.js";
6
+ export type { Environment, PresetChains } from "./presets.js";
7
+
8
+ // Types
9
+ export type { ChainClient, ChainClientConfig, ChainEntry } from "./types.js";
10
+
11
+ // Re-export from host
12
+ export { isInsideContainer, isInsideContainerSync } from "@parity/product-sdk-host";
package/src/presets.ts ADDED
@@ -0,0 +1,221 @@
1
+ import type { ChainDefinition } from "polkadot-api";
2
+ import { BULLETIN_RPCS } from "@parity/product-sdk-host";
3
+ import { createChainClient } from "./clients.js";
4
+ import type { ChainClient } from "./types.js";
5
+
6
+ // Type-only imports — erased at compile time, zero bundle cost.
7
+ // These give us per-chain TypedApi types without importing runtime descriptor data.
8
+ import type { polkadot_asset_hub as PolkadotAssetHubDef } from "@parity/product-sdk-descriptors/polkadot-asset-hub";
9
+ import type { kusama_asset_hub as KusamaAssetHubDef } from "@parity/product-sdk-descriptors/kusama-asset-hub";
10
+ import type { paseo_asset_hub as PaseoAssetHubDef } from "@parity/product-sdk-descriptors/paseo-asset-hub";
11
+ import type { bulletin as BulletinDef } from "@parity/product-sdk-descriptors/bulletin";
12
+ import type { individuality as IndividualityDef } from "@parity/product-sdk-descriptors/individuality";
13
+
14
+ /** Known network environment with built-in descriptors and RPC endpoints. */
15
+ export type Environment = "polkadot" | "kusama" | "paseo";
16
+
17
+ /** Environments where all chains (asset hub, bulletin, individuality) are live. */
18
+ const AVAILABLE_ENVIRONMENTS: Set<Environment> = new Set(["paseo"]);
19
+
20
+ const rpcs = {
21
+ polkadot: {
22
+ assetHub: [
23
+ "wss://polkadot-asset-hub-rpc.polkadot.io",
24
+ "wss://sys.ibp.network/asset-hub-polkadot",
25
+ ],
26
+ bulletin: [...BULLETIN_RPCS.polkadot],
27
+ individuality: [] as string[],
28
+ },
29
+ kusama: {
30
+ assetHub: [
31
+ "wss://kusama-asset-hub-rpc.polkadot.io",
32
+ "wss://sys.ibp.network/asset-hub-kusama",
33
+ ],
34
+ bulletin: [...BULLETIN_RPCS.kusama],
35
+ individuality: [] as string[],
36
+ },
37
+ paseo: {
38
+ assetHub: [
39
+ "wss://asset-hub-paseo-rpc.n.dwellir.com",
40
+ "wss://sys.ibp.network/asset-hub-paseo",
41
+ ],
42
+ bulletin: [...BULLETIN_RPCS.paseo],
43
+ individuality: ["wss://paseo-people-next-rpc.polkadot.io"],
44
+ },
45
+ } as const;
46
+
47
+ /**
48
+ * Lazy-load descriptors for a specific environment.
49
+ * Only imports the chains needed — avoids bundling all 5 chains when
50
+ * a consumer only uses one environment.
51
+ */
52
+ async function loadDescriptors(env: Environment) {
53
+ const assetHubImport = {
54
+ polkadot: () => import("@parity/product-sdk-descriptors/polkadot-asset-hub"),
55
+ kusama: () => import("@parity/product-sdk-descriptors/kusama-asset-hub"),
56
+ paseo: () => import("@parity/product-sdk-descriptors/paseo-asset-hub"),
57
+ }[env]();
58
+
59
+ const [ahMod, { bulletin }, { individuality }] = await Promise.all([
60
+ assetHubImport,
61
+ import("@parity/product-sdk-descriptors/bulletin"),
62
+ import("@parity/product-sdk-descriptors/individuality"),
63
+ ]);
64
+
65
+ // Extract the asset hub descriptor (the named export varies per environment)
66
+ const assetHub =
67
+ "polkadot_asset_hub" in ahMod
68
+ ? ahMod.polkadot_asset_hub
69
+ : "kusama_asset_hub" in ahMod
70
+ ? ahMod.kusama_asset_hub
71
+ : (ahMod as typeof import("@parity/product-sdk-descriptors/paseo-asset-hub"))
72
+ .paseo_asset_hub;
73
+
74
+ return { assetHub, bulletin, individuality };
75
+ }
76
+
77
+ /** Maps each environment to its asset hub descriptor type. */
78
+ type AssetHubDescriptors = {
79
+ polkadot: typeof PolkadotAssetHubDef;
80
+ kusama: typeof KusamaAssetHubDef;
81
+ paseo: typeof PaseoAssetHubDef;
82
+ };
83
+
84
+ /** The chain shape returned by {@link getChainAPI} for a given environment. */
85
+ export type PresetChains<E extends Environment> = {
86
+ assetHub: AssetHubDescriptors[E];
87
+ bulletin: typeof BulletinDef;
88
+ individuality: typeof IndividualityDef;
89
+ };
90
+
91
+ /**
92
+ * Get a chain client for a known environment with built-in descriptors and RPCs.
93
+ *
94
+ * This is the **zero-config** path — no need to import descriptors or specify
95
+ * endpoints. For custom chains or BYOD descriptors, use
96
+ * {@link createChainClient} instead.
97
+ *
98
+ * Returns the same {@link ChainClient} type as `createChainClient`, with
99
+ * `assetHub`, `bulletin`, and `individuality` chain keys.
100
+ *
101
+ * @example
102
+ * ```ts
103
+ * import { getChainAPI } from "@parity/product-sdk-chain-client";
104
+ *
105
+ * const client = await getChainAPI("paseo");
106
+ *
107
+ * // Fully typed — no descriptor imports needed
108
+ * const account = await client.assetHub.query.System.Account.getValue(addr);
109
+ * const fee = await client.bulletin.query.TransactionStorage.ByteFee.getValue();
110
+ *
111
+ * // Raw client for advanced use (e.g., InkSdk for contracts)
112
+ * import { createInkSdk } from "@polkadot-api/sdk-ink";
113
+ * const inkSdk = createInkSdk(client.raw.assetHub, { atBest: true });
114
+ *
115
+ * client.destroy();
116
+ * ```
117
+ */
118
+ export async function getChainAPI<E extends Environment>(
119
+ env: E,
120
+ ): Promise<ChainClient<PresetChains<E>>> {
121
+ if (!AVAILABLE_ENVIRONMENTS.has(env)) {
122
+ throw new Error(`Chain API for "${env}" is not yet available`);
123
+ }
124
+
125
+ const descriptors = await loadDescriptors(env);
126
+ const envRpcs = rpcs[env];
127
+
128
+ return createChainClient({
129
+ chains: {
130
+ assetHub: descriptors.assetHub,
131
+ bulletin: descriptors.bulletin,
132
+ individuality: descriptors.individuality,
133
+ },
134
+ rpcs: {
135
+ assetHub: [...envRpcs.assetHub],
136
+ bulletin: [...envRpcs.bulletin],
137
+ individuality: [...envRpcs.individuality],
138
+ },
139
+ }) as Promise<ChainClient<PresetChains<E>>>;
140
+ }
141
+
142
+ if (import.meta.vitest) {
143
+ const { test, expect, beforeEach } = import.meta.vitest;
144
+ const { destroyAll } = await import("./clients.js");
145
+
146
+ // Test-only genesis hashes for assertion — not used in production code.
147
+ const GENESIS = {
148
+ polkadot_asset_hub: "0x68d56f15f85d3136970ec16946040bc1752654e906147f7e43e9d539d7c3de2f",
149
+ kusama_asset_hub: "0x48239ef607d7928874027a43a67689209727dfb3d3dc5e5b03a39bdc2eda771a",
150
+ paseo_asset_hub: "0xd6eec26135305a8ad257a20d003357284c8aa03d0bdb2b357ab0a22371e11ef2",
151
+ bulletin: "0x744960c32e3a3df5440e1ecd4d34096f1ce2230d7016a5ada8a765d5a622b4ea",
152
+ individuality: "0xd01475fde5d0592989b7715ae1d2e89fdb4f8c7688c09c850d75e1d4bdb47d64",
153
+ } as const;
154
+
155
+ beforeEach(() => {
156
+ destroyAll();
157
+ });
158
+
159
+ // --- GENESIS constants ---
160
+
161
+ test("genesis constants are valid hex hashes", () => {
162
+ for (const hash of Object.values(GENESIS)) {
163
+ expect(hash).toMatch(/^0x[a-f0-9]{64}$/);
164
+ }
165
+ });
166
+
167
+ // --- RPC config ---
168
+
169
+ test("rpcs defined for all environments", () => {
170
+ for (const env of ["polkadot", "kusama", "paseo"] as const) {
171
+ const envRpcs = rpcs[env];
172
+ expect(envRpcs.assetHub.length).toBeGreaterThan(0);
173
+ }
174
+ });
175
+
176
+ test("paseo has RPCs for all chains", () => {
177
+ const envRpcs = rpcs.paseo;
178
+ expect(envRpcs.bulletin.length).toBeGreaterThan(0);
179
+ expect(envRpcs.individuality.length).toBeGreaterThan(0);
180
+ });
181
+
182
+ // --- getChainAPI ---
183
+
184
+ test("polkadot and kusama throw as not yet available", async () => {
185
+ await expect(getChainAPI("polkadot")).rejects.toThrow("not yet available");
186
+ await expect(getChainAPI("kusama")).rejects.toThrow("not yet available");
187
+ });
188
+
189
+ // --- loadDescriptors ---
190
+
191
+ test("loadDescriptors returns descriptors with genesis hashes for paseo", async () => {
192
+ const descriptors = await loadDescriptors("paseo");
193
+ expect(descriptors).toBeDefined();
194
+ expect(descriptors.assetHub).toBeDefined();
195
+ expect(descriptors.bulletin).toBeDefined();
196
+ expect(descriptors.individuality).toBeDefined();
197
+ expect(descriptors.assetHub.genesis).toBe(GENESIS.paseo_asset_hub);
198
+ expect(descriptors.bulletin.genesis).toBe(GENESIS.bulletin);
199
+ expect(descriptors.individuality.genesis).toBe(GENESIS.individuality);
200
+ });
201
+
202
+ test("loadDescriptors returns correct asset hub per environment", async () => {
203
+ const polkadot = await loadDescriptors("polkadot");
204
+ const kusama = await loadDescriptors("kusama");
205
+ const paseo = await loadDescriptors("paseo");
206
+ expect(polkadot.assetHub.genesis).toBe(GENESIS.polkadot_asset_hub);
207
+ expect(kusama.assetHub.genesis).toBe(GENESIS.kusama_asset_hub);
208
+ expect(paseo.assetHub.genesis).toBe(GENESIS.paseo_asset_hub);
209
+ // bulletin and individuality are the same across environments
210
+ expect(polkadot.bulletin.genesis).toBe(paseo.bulletin.genesis);
211
+ expect(polkadot.individuality.genesis).toBe(paseo.individuality.genesis);
212
+ });
213
+
214
+ // --- AVAILABLE_ENVIRONMENTS ---
215
+
216
+ test("only paseo is currently available", () => {
217
+ expect(AVAILABLE_ENVIRONMENTS.has("paseo")).toBe(true);
218
+ expect(AVAILABLE_ENVIRONMENTS.has("polkadot")).toBe(false);
219
+ expect(AVAILABLE_ENVIRONMENTS.has("kusama")).toBe(false);
220
+ });
221
+ }
@@ -0,0 +1,57 @@
1
+ import { getHostProvider } from "@parity/product-sdk-host";
2
+ import type { JsonRpcProvider } from "polkadot-api/ws-provider/web";
3
+
4
+ /**
5
+ * Create a PAPI-compatible JSON-RPC provider for a chain.
6
+ *
7
+ * Routes connections through the host provider (`@parity/product-sdk-host`).
8
+ * The SDK is designed to run exclusively inside a host container.
9
+ *
10
+ * @throws {Error} If the host provider is unavailable (not inside a container).
11
+ */
12
+ export async function createProvider(genesisHash: string): Promise<JsonRpcProvider> {
13
+ const hostProvider = await getHostProvider(genesisHash as `0x${string}`);
14
+ if (!hostProvider) {
15
+ throw new Error(
16
+ `Host provider unavailable for chain ${genesisHash}. Ensure you are running inside a host container (Polkadot Browser / Desktop).`,
17
+ );
18
+ }
19
+ return hostProvider;
20
+ }
21
+
22
+ if (import.meta.vitest) {
23
+ const { test, expect, vi, beforeEach } = import.meta.vitest;
24
+
25
+ // Shared state between hoisted mocks and tests
26
+ const state = vi.hoisted(() => ({
27
+ fakeProvider: (() => {}) as unknown as JsonRpcProvider,
28
+ hostProviderCalls: [] as unknown[][],
29
+ hostProviderAvailable: true,
30
+ }));
31
+
32
+ vi.mock("@parity/product-sdk-host", async (importOriginal) => ({
33
+ ...(await importOriginal<typeof import("@parity/product-sdk-host")>()),
34
+ getHostProvider: async (...args: unknown[]) => {
35
+ state.hostProviderCalls.push(args);
36
+ if (!state.hostProviderAvailable) return null;
37
+ return state.fakeProvider;
38
+ },
39
+ }));
40
+
41
+ beforeEach(() => {
42
+ state.hostProviderCalls = [];
43
+ state.hostProviderAvailable = true;
44
+ });
45
+
46
+ test("returns host provider when available", async () => {
47
+ const result = await createProvider("0xabc");
48
+ expect(result).toBe(state.fakeProvider);
49
+ expect(state.hostProviderCalls.length).toBe(1);
50
+ expect(state.hostProviderCalls[0][0]).toBe("0xabc");
51
+ });
52
+
53
+ test("throws when host provider unavailable", async () => {
54
+ state.hostProviderAvailable = false;
55
+ await expect(createProvider("0xabc")).rejects.toThrow(/Host provider unavailable/);
56
+ });
57
+ }