@parity/product-sdk 0.0.0-dev.312.0 → 0.0.0-dev.329.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.
Files changed (57) hide show
  1. package/dist/address/index.d.ts +3 -1
  2. package/dist/{chunk-BRZNHTLQ.js → chunk-7GM3HUZF.js} +2 -2
  3. package/dist/chunk-7GM3HUZF.js.map +1 -0
  4. package/dist/chunk-TUXU2VPS.js +14 -0
  5. package/dist/chunk-TUXU2VPS.js.map +1 -0
  6. package/dist/{chunk-DHRCWMY5.js → chunk-VWD6HK2C.js} +29 -20
  7. package/dist/chunk-VWD6HK2C.js.map +1 -0
  8. package/dist/core/index.d.ts +50 -3
  9. package/dist/core/index.js +3 -2
  10. package/dist/{dotns-bswWAmR2.d.ts → dotns-CtmOwVQW.d.ts} +2 -2
  11. package/dist/identity/index.d.ts +118 -89
  12. package/dist/identity/index.js +200 -78
  13. package/dist/identity/index.js.map +1 -1
  14. package/dist/index.d.ts +3 -53
  15. package/dist/index.js +3 -2
  16. package/dist/nfts/index.d.ts +1 -0
  17. package/dist/nfts/index.js +3 -0
  18. package/dist/nfts/index.js.map +1 -0
  19. package/dist/react/index.d.ts +5 -5
  20. package/dist/react/index.js +4 -3
  21. package/dist/react/index.js.map +1 -1
  22. package/dist/renderer/index.d.ts +1 -0
  23. package/dist/renderer/index.js +3 -0
  24. package/dist/renderer/index.js.map +1 -0
  25. package/dist/testing/index.d.ts +2 -2
  26. package/dist/testing/index.js +3 -5
  27. package/dist/testing/index.js.map +1 -1
  28. package/dist/{types-B5Zx4RNq.d.ts → types-BpWw-OJl.d.ts} +19 -9
  29. package/package.json +23 -12
  30. package/src/core/createApp.test.ts +194 -0
  31. package/src/core/createApp.ts +35 -22
  32. package/src/core/local-storage-api.ts +74 -0
  33. package/src/core/types.ts +18 -7
  34. package/src/identity/dotns-abis.ts +44 -9
  35. package/src/identity/dotns-addresses.test.ts +536 -0
  36. package/src/identity/dotns-addresses.ts +320 -0
  37. package/src/identity/dotns-errors.ts +2 -0
  38. package/src/identity/dotns-namehash.ts +2 -2
  39. package/src/identity/dotns-registry.test.ts +158 -3
  40. package/src/identity/dotns-registry.ts +71 -73
  41. package/src/identity/dotns.ts +2 -2
  42. package/src/identity/index.test.ts +43 -0
  43. package/src/identity/index.ts +10 -6
  44. package/src/identity/types.ts +0 -19
  45. package/src/index.ts +3 -2
  46. package/src/individuality/contract.test.ts +426 -2
  47. package/src/nfts/contract.test.ts +58 -0
  48. package/src/nfts/index.ts +8 -0
  49. package/src/react/context.ts +1 -1
  50. package/src/react/index.ts +1 -1
  51. package/src/react/provider.tsx +3 -3
  52. package/src/renderer/index.ts +10 -0
  53. package/src/testing.ts +14 -11
  54. package/dist/chunk-BRZNHTLQ.js.map +0 -1
  55. package/dist/chunk-DHRCWMY5.js.map +0 -1
  56. package/src/identity/product-account.test.ts +0 -130
  57. package/src/identity/product-account.ts +0 -115
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/identity/dotns-namehash.ts","../src/identity/dotns.ts"],"names":["hexToBytes","bytesToHex"],"mappings":";;;;AAyCO,IAAM,QAAA,GAAW;AAExB,IAAM,SAAA,GAAY,CAAA,EAAA,EAAK,IAAA,CAAK,MAAA,CAAO,EAAE,CAAC,CAAA,CAAA;AAEtC,IAAM,OAAO,CAAC,CAAA,KAA0B,IAAI,WAAA,EAAY,CAAE,OAAO,CAAC,CAAA;AAGlE,SAAS,SAAA,CAAU,QAAoB,KAAA,EAA2B;AAC9D,EAAA,MAAM,QAAA,GAAW,IAAI,UAAA,CAAW,EAAE,CAAA;AAClC,EAAA,QAAA,CAAS,GAAA,CAAI,QAAQ,CAAC,CAAA;AACtB,EAAA,QAAA,CAAS,IAAI,SAAA,CAAU,IAAA,CAAK,KAAK,CAAC,GAAG,EAAE,CAAA;AACvC,EAAA,OAAO,UAAU,QAAQ,CAAA;AAC7B;AAcO,SAAS,SAAS,MAAA,EAA0B;AAC/C,EAAA,MAAM,KAA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O,SAAS,eAAe,OAAA,EAAgC;AAC3D,EAAA,OAAO,mBAAA,CAAoB,cAAA,CAAe,OAAO,CAAC,CAAA;AACtD","file":"chunk-BRZNHTLQ.js","sourcesContent":["// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * DotNS namehash.\n *\n * ENS-style recursive hashing, but rooted at the network's TLD node rather than\n * the empty root — matching `DotnsRegistry` (`contracts/registry/DotnsRegistry.sol`\n * `_namehash`) and `LabelUtils.namehashUnder`.\n *\n * labelhash(l) = keccak256(utf8(l))\n * node(parent, l) = keccak256(parent ‖ labelhash(l))\n * node(\"alice.paseo\") = node(tldNode, \"alice\")\n * node(\"bob.alice.paseo\") = node(node(tldNode, \"alice\"), \"bob\")\n *\n * The root is **per network**, not a constant. `DotnsProtocolRegistry.initialize`\n * fixes it once from a deploy-time label — `.dot` on Paseo Asset Hub Previewnet,\n * `.paseo` on Next V2 — and publishes it as `tld()` / `tldNode()`. Hashing under\n * the wrong root yields a node the chain has never written to, so every lookup\n * reports \"unregistered\" with no error anywhere. That is why {@link namehash}\n * takes the root rather than assuming one; `resolveTld` in `./dotns-registry.js`\n * is what asks the chain for it.\n */\nimport { bytesToHex, hexToBytes, keccak256 } from \"@parity/product-sdk-crypto\";\n\n/**\n * A network's DotNS top-level domain: the suffix names are spelled with, and\n * the node every one of its names hashes onto.\n *\n * The two must agree — `node` is `namehash(0, labelhash(label))` of `suffix`'s\n * label — so build one with {@link dotNsTld} rather than by hand, and check an\n * externally supplied pair with {@link isConsistentDotNsTld}. A `.paseo` suffix\n * carrying the `.dot` node is exactly the defect this type exists to prevent.\n */\nexport interface DotNsTld {\n /** Suffix including the leading dot, as `protocolRegistry.tld()` returns it. */\n suffix: string;\n /** Namehash of the TLD label, as `protocolRegistry.tldNode()` returns it. */\n node: `0x${string}`;\n}\n\n/** The `.dot` TLD node. Mirrors the `DotnsConstants.DOT_NODE` the contracts removed in `b4096968`. */\nexport const DOT_NODE = \"0x3fce7d1364a893e213bc4212792b517ffc88f5b13b86c8ef9c8d390c3a1370ce\";\n\nconst ZERO_NODE = `0x${\"00\".repeat(32)}`;\n\nconst utf8 = (s: string): Uint8Array => new TextEncoder().encode(s);\n\n/** `keccak256(parent ‖ labelhash(label))`, the one hash step every node is built from. */\nfunction nodeUnder(parent: Uint8Array, label: string): Uint8Array {\n const combined = new Uint8Array(64);\n combined.set(parent, 0);\n combined.set(keccak256(utf8(label)), 32);\n return keccak256(combined);\n}\n\n/**\n * Build a {@link DotNsTld} from a TLD suffix, deriving the node the same way the\n * contract does.\n *\n * Mirrors `DotnsProtocolRegistry.initialize`, which sets\n * `_tldNode = namehashUnder(bytes32(0), labelhash(tldLabel))`. Because the node\n * is a pure function of the label, a client only ever needs the suffix — reading\n * `tldNode()` is a cross-check, never the source.\n *\n * Accepts `\".paseo\"` or `\"paseo\"`: `tld()` returns the dotted form while\n * `initialize` and the deploy pipeline speak the bare label.\n */\nexport function dotNsTld(suffix: string): DotNsTld {\n const label = suffix.startsWith(\".\") ? suffix.slice(1) : suffix;\n return {\n suffix: `.${label}`,\n node: `0x${bytesToHex(nodeUnder(hexToBytes(ZERO_NODE.slice(2)), label))}`,\n };\n}\n\n/**\n * Whether a {@link DotNsTld} could have come from a real deployment.\n *\n * Three ways a pair fails, all of which produce silently wrong nodes rather\n * than errors if they reach {@link namehash}:\n *\n * - the node is not the derivation of the suffix (a caller mixing `.paseo`\n * with `DOT_NODE`);\n * - the suffix is empty, or the node is zero — what a pre-`b4096968` registry\n * proxy reports after an upgrade with no reinitializer, since `_tld` and\n * `_tldNode` are then still at their defaults and *both getters succeed*;\n * - the suffix is not a single label, which `initialize` rejects outright.\n *\n * Returns a boolean rather than a `Result` to keep this module free of the\n * error type; callers with an error channel (`resolveTld`) map `false` to an\n * `err` carrying the offending value.\n */\nexport function isConsistentDotNsTld(tld: DotNsTld): boolean {\n const label = tld.suffix.startsWith(\".\") ? tld.suffix.slice(1) : tld.suffix;\n if (label.length === 0 || label.includes(\".\")) return false;\n if (tld.node.toLowerCase() === ZERO_NODE) return false;\n return dotNsTld(label).node.toLowerCase() === tld.node.toLowerCase();\n}\n\n/** The `.dot` TLD, for a deployment that uses it. Not a default: pass it explicitly. */\nexport const DOT_TLD: DotNsTld = { suffix: \".dot\", node: DOT_NODE };\n\n/**\n * Drop `suffix` from the end of `name`, leaving the labels beneath it.\n *\n * Strips by the suffix's own length, which is the whole point: the same logic\n * written as `slice(0, -4)` turns `alice.paseo` into `alice.pa`, and every\n * lookup for that name then asks about a subname nobody registered. A name that\n * does not carry the suffix is returned unchanged, so a foreign suffix stays\n * visible to whatever validates next.\n *\n * Lives here rather than in `./dotns.js` so the one copy is reachable from this\n * module without pulling its heavier imports in.\n */\nexport function stripSuffix(name: string, suffix: string): string {\n return name.endsWith(suffix) ? name.slice(0, -suffix.length) : name;\n}\n\n/**\n * Compute the DotNS node hash for a name like `\"alice.paseo\"` or\n * `\"bob.alice.paseo\"`, rooted at `tld`.\n *\n * The trailing suffix is the TLD (folded into `tld.node`); remaining labels are\n * hashed most-significant-last, so `bob.alice.paseo` layers `bob` on top of\n * `alice` on top of the TLD. Input is used as-is — normalize with\n * `normalizeDotNsName` first if needed.\n *\n * `tld` is required rather than defaulted, because a default that is correct on\n * one deployment is the defect this module was fixed for. It is also not\n * validated here: a name whose suffix belongs to another deployment hashes to a\n * node under `tld` instead of being refused, since this function returns a hash\n * and has nowhere to report a complaint. The entry points in\n * `./dotns-registry.js` do that check, where there is an error channel.\n *\n * @returns the 32-byte node as a `0x`-prefixed hex string.\n */\nexport function namehash(name: string, tld: DotNsTld): `0x${string}` {\n const trimmed = stripSuffix(name, tld.suffix);\n // \"\" → the bare TLD node; otherwise split into labels.\n const labels = trimmed === \"\" ? [] : trimmed.split(\".\");\n // Layer from the TLD outward: labels are given left-most-first\n // (bob.alice), but must be applied right-to-left onto the parent.\n // Annotated: hexToBytes yields ArrayBufferLike, keccak256 yields ArrayBuffer.\n let node: Uint8Array = hexToBytes(tld.node.slice(2));\n for (let i = labels.length - 1; i >= 0; i--) {\n node = nodeUnder(node, labels[i]);\n }\n return `0x${bytesToHex(node)}`;\n}\n","// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * DotNS (Polkadot Name Service) utilities\n *\n * Name validation and normalization. Every helper here takes the deployment's\n * TLD suffix rather than assuming `.dot`: the TLD is fixed per network when the\n * contracts initialise, so the same string is a valid name on one deployment\n * and meaningless on another. `resolveTld` in `./dotns-registry.js` is what\n * asks the chain which suffix is in play.\n */\n\nimport { accountIdBytes } from \"@parity/product-sdk-address\";\nimport { bytesToHex, hexToBytes } from \"@parity/product-sdk-crypto\";\nimport { stripSuffix } from \"./dotns-namehash.js\";\nimport type {\n ChainDefinition,\n PalletsTypedef,\n PlainDescriptor,\n RuntimeDescriptor,\n SS58String,\n StorageDescriptor,\n TxDescriptor,\n} from \"polkadot-api\";\n\ntype AnyDescriptorEntry<T> = Record<string, Record<string, T>>;\n\ntype PeopleUsernameStorage = {\n Resources: {\n UsernameOwnerOf: StorageDescriptor<[Uint8Array], SS58String, true, never>;\n };\n};\n\ntype PeopleUsernamePallets = PalletsTypedef<\n PeopleUsernameStorage,\n AnyDescriptorEntry<TxDescriptor<any>>,\n AnyDescriptorEntry<PlainDescriptor<any>>,\n AnyDescriptorEntry<PlainDescriptor<any>>,\n AnyDescriptorEntry<PlainDescriptor<any>>,\n AnyDescriptorEntry<RuntimeDescriptor<any, any>>\n>;\n\n/**\n * Descriptor narrowed to \"any chain that exposes `Resources.UsernameOwnerOf`\".\n *\n * Used as the input to `signMessageWithDotNsIdentity` so the SDK doesn't pin\n * a specific People-chain genesis — anything with the right storage shape\n * (paseo-individuality today, future People Lite, etc.) is accepted.\n */\nexport type PeopleUsernameChain = ChainDefinition & {\n descriptors: Promise<unknown> & {\n pallets: PeopleUsernamePallets;\n };\n};\n\n/**\n * Minimal typed-api shape required to resolve a username on a People chain.\n *\n * This is a narrow structural type — anything with the right\n * `query.Resources.UsernameOwnerOf.getValue` shape works, including a real\n * `TypedApi<PeopleUsernameChain>` slice of a `ChainClient` or a hand-rolled\n * test double.\n */\nexport type PeopleUsernameQueryApi = {\n query: {\n Resources: {\n UsernameOwnerOf: {\n getValue: (key: Uint8Array) => Promise<SS58String | undefined>;\n };\n };\n };\n};\n\n/**\n * Whether `name` is a single registrable label under `suffix`.\n *\n * `suffix` is the deployment's own TLD, including its leading dot, as\n * `resolveTld` reports it — `\".dot\"` on Paseo Asset Hub Previewnet, `\".paseo\"`\n * on Next V2. It is required rather than defaulted, because a name is only\n * valid *relative to a deployment*: `alice.dot` is registrable on one network\n * and meaningless on the other, and a default would silently pick one.\n *\n * @param name - Name to validate, already normalized by {@link normalizeDotNsName}\n * @param suffix - The deployment's TLD suffix, e.g. `\".paseo\"`\n */\nexport function isValidDotNsName(name: string, suffix: string): boolean {\n if (!name.endsWith(suffix)) return false;\n return isValidLabel(stripSuffix(name, suffix));\n}\n\n/**\n * One canonical DNS label, matching the on-chain rule.\n *\n * `StringUtils.isSingleLabel` allows lowercase ASCII, digits and non-edge\n * hyphens up to 63 characters, and the registrar additionally requires 3.\n */\nfunction isValidLabel(label: string): boolean {\n if (label.length < 3 || label.length > 63) return false;\n return /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label);\n}\n\n/**\n * Whether a name can be resolved: one or more valid labels under `suffix`.\n *\n * Broader than {@link isValidDotNsName} on purpose. The registrar only mints\n * single labels, so registration keeps the stricter rule, but the registry\n * supports subnodes and `namehash` hashes them, so `bob.alice.paseo` is\n * resolvable even though it is not registrable.\n *\n * @param name - Name to check, already normalized by {@link normalizeDotNsName}\n * @param suffix - The deployment's TLD suffix, e.g. `\".paseo\"`\n */\nexport function isResolvableDotNsName(name: string, suffix: string): boolean {\n if (!name.endsWith(suffix)) return false;\n const labels = stripSuffix(name, suffix).split(\".\");\n return labels.length > 0 && labels.every(isValidLabel);\n}\n\n/**\n * Normalize a DotNS name for the deployment identified by `suffix`.\n *\n * Case-folds, applies NFC, trims surrounding whitespace, and drops a single\n * trailing root dot, so `Alice.PASEO.` keys the same as `alice.paseo`. This\n * mirrors `normalize_host` in truapi-server, which is what turns a URL into a\n * dotNS identifier — a name arriving from navigation has to key identically\n * here or the two layers disagree about the same input.\n *\n * The NFC step is defensive only: {@link isValidLabel} and the on-chain\n * `StringUtils.isSingleLabel` both allow lowercase ASCII alone, so no name that\n * survives validation can differ between its composed and decomposed spellings.\n * It costs nothing and it keeps this function honest if the label rule ever\n * widens.\n *\n * **The suffix is appended only when `name` contains no dot at all.** A bare\n * label is the friendly path and gets the deployment's suffix; anything already\n * carrying a dot is left exactly as written, so a name from another deployment\n * survives to be refused by validation rather than being buried under our own\n * suffix. Appending on `!endsWith(suffix)` instead would turn `alice.dot` into\n * `alice.dot.paseo`, which is a well-formed subname and would resolve silently\n * to a node nobody owns.\n *\n * The cost of that rule: a bare multi-label name such as `bob.alice` is no\n * longer completed to `bob.alice.paseo`. Distinguishing it from `alice.dot`\n * would require a hardcoded list of every network's TLD, and there are already\n * more TLDs deployed than any such list contains.\n *\n * @param name - Name to normalize\n * @param suffix - The deployment's TLD suffix, e.g. `\".paseo\"`\n */\nexport function normalizeDotNsName(name: string, suffix: string): string {\n const folded = name.trim().normalize(\"NFC\").toLowerCase();\n const normalized = folded.endsWith(\".\") ? folded.slice(0, -1) : folded;\n return normalized.includes(\".\") ? normalized : normalized + suffix;\n}\n\n// `resolveDotNs` / `reverseDotNs` / `isDotNsAvailable` now live in\n// `./dotns-registry.ts` (real `Result`-returning registry calls), replacing the\n// throwing skeletons that used to sit here. See that module + the design doc.\n\n/**\n * Resolve a People / People Lite username to its owning account.\n *\n * Queries `Resources.UsernameOwnerOf` on the caller-supplied typed-api fragment.\n * The returned value is the SS58 address the storage yields, or `null` when no\n * owner is registered for that username.\n *\n * Returns SS58 rather than hex because that is both the form the storage yields\n * and the form `Resources.Consumers` is keyed by, so reading an account's\n * usernames from this result needs no conversion. Callers that want the raw\n * 32-byte key use `accountIdBytes` from `@parity/product-sdk-address`, and\n * {@link accountIdToHex} for the hex form.\n *\n * The `username` is UTF-8 encoded as-is — no normalization is applied. Pass\n * the exact byte string the chain stores (typically with the `.dot` suffix).\n *\n * @internal Exposed for unit testing. Consumers should use\n * `wallet.signMessageWithDotNsIdentity` instead, which orchestrates the\n * chain-connection lifecycle.\n */\nexport async function resolvePeopleUsernameOwner(\n username: string,\n peopleApi: PeopleUsernameQueryApi,\n): Promise<SS58String | null> {\n const owner = await peopleApi.query.Resources.UsernameOwnerOf.getValue(\n new TextEncoder().encode(username),\n );\n return owner ?? null;\n}\n\nfunction assertHex(value: string): `0x${string}` {\n if (!/^0x[0-9a-fA-F]*$/.test(value)) {\n throw new Error(`Expected 0x-prefixed hex string, got ${value}`);\n }\n return value as `0x${string}`;\n}\n\nexport function accountIdHexToBytes(accountId: `0x${string}`): Uint8Array {\n const bytes = hexToBytes(assertHex(accountId).slice(2));\n if (bytes.length !== 32) {\n throw new Error(`Expected 32-byte AccountId, got ${bytes.length} bytes`);\n }\n return bytes;\n}\n\n/** Throws on any input that is not exactly 32 bytes, rather than padding it. */\nexport function accountIdBytesToHex(bytes: Uint8Array): `0x${string}` {\n if (bytes.length !== 32) {\n throw new Error(`Expected 32-byte AccountId, got ${bytes.length} bytes`);\n }\n return `0x${bytesToHex(bytes)}`;\n}\n\n/**\n * The inverse of {@link accountIdHexToBytes}.\n *\n * No in-repo caller: this is the migration path for consumers, after\n * `resolvePeopleUsernameOwner` changed from hex to SS58. Not dead code.\n */\nexport function accountIdToHex(address: string): `0x${string}` {\n return accountIdBytesToHex(accountIdBytes(address));\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/createApp.ts"],"names":["err"],"mappings":";;;;;;;;;;AA0CA,IAAM,GAAA,GAAM,aAAa,KAAK,CAAA;AA0C9B,eAAsB,UAAU,MAAA,EAAiC;AAE7D,EAAA,IAAI,OAAO,QAAA,EAAU;AACjB,IAAA,SA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EAAU;AACX,IAAA,MAAM,IAAI,MAAM,wDAAwD,CAAA;AAAA,EAC5E;AACA,EAAA,OAAO,QAAA;AACX","file":"chunk-DHRCWMY5.js","sourcesContent":["// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * createApp - Main entry point for the Product SDK\n *\n * Creates an App instance with wallet, storage, chain, and cloud storage APIs.\n */\n\nimport type { ChainDefinition } from \"polkadot-api\";\nimport type {\n App,\n AppConfig,\n WalletApi,\n ChainApi,\n Account,\n CloudStorageApi,\n LocalStorageApi,\n} from \"./types.js\";\nimport { configure, createLogger } from \"@parity/product-sdk-logger\";\nimport { createLocalKvStore } from \"@parity/product-sdk-local-storage\";\nimport { SignerManager } from \"@parity/product-sdk-signer\";\nimport {\n CloudStorageClient,\n ProductCloudStorageError,\n calculateCid,\n createLazySigner,\n} from \"@parity/product-sdk-cloud-storage\";\nimport { err, ok } from \"@parity/result\";\nimport {\n createChainClient,\n getClient,\n isConnected,\n destroyAll,\n} from \"@parity/product-sdk-chain-client\";\nimport { accountIdBytes } from \"@parity/product-sdk-address\";\nimport { getAccountsProvider } from \"@parity/product-sdk-host\";\nimport {\n accountIdBytesToHex,\n type PeopleUsernameQueryApi,\n resolvePeopleUsernameOwner,\n} from \"../identity/dotns.js\";\n\nconst log = createLogger(\"app\");\n\n/**\n * Create a new Product SDK app instance\n *\n * @param config - Application configuration\n * @returns App instance with all APIs\n *\n * @example\n * ```ts\n * import { createApp } from '@parity/product-sdk';\n *\n * // Default: cloud storage enabled with paseo environment\n * const app = await createApp({\n * name: 'my-app',\n * logLevel: 'info',\n * });\n *\n * // Custom cloud storage environment\n * const prodApp = await createApp({\n * name: 'my-app',\n * cloudStorage: { environment: 'polkadot' },\n * });\n *\n * // Disable cloud storage entirely\n * const noCloudStorageApp = await createApp({\n * name: 'my-app',\n * cloudStorage: false,\n * });\n *\n * // Connect wallet\n * const { accounts } = await app.wallet.connect();\n *\n * // Use storage\n * await app.localStorage.set('key', 'value');\n *\n * // Use cloud storage (check for null if it might be disabled)\n * if (app.cloudStorage) {\n * const cid = await app.cloudStorage.upload('hello world');\n * }\n * ```\n */\nexport async function createApp(config: AppConfig): Promise<App> {\n // Set log level if specified\n if (config.logLevel) {\n configure({ level: config.logLevel });\n }\n\n log.info(\"Creating Product SDK app\", { name: config.name });\n\n // Initialize storage (container-only - will throw if not in container)\n const localKvStore = await createLocalKvStore({ prefix: config.name });\n\n // Initialize signer manager\n const signerManager = new SignerManager({\n dappName: config.name,\n });\n\n // Initialize cloud storage client (configurable, defaults to paseo).\n //\n // The signer is wrapped lazily so the cloud storage client can be built before\n // an account is selected. Uploads will throw a clear error if no signer\n // is available at submission time. Reads (fetch / fetchJson) don't need\n // a signer, so they work regardless of whether an account is selected --\n // but they are container-only and throw CloudStorageHostUnavailableError\n // outside a host container (no IPFS-gateway fallback).\n const cloudStorageEnabled = config.cloudStorage !== false;\n const cloudStorageEnvironment =\n typeof config.cloudStorage === \"object\" ? config.cloudStorage.environment : \"paseo\";\n const cloudStorageClient = cloudStorageEnabled\n ? await CloudStorageClient.create({\n environment: cloudStorageEnvironment,\n signer: createLazySigner(() => signerManager.getSigner()),\n })\n : null;\n\n if (cloudStorageEnabled) {\n log.debug(\"Cloud Storage client (Bulletin) initialized\", {\n environment: cloudStorageEnvironment,\n });\n } else {\n log.debug(\"Cloud Storage client disabled\");\n }\n\n // Create storage API adapter\n const localStorageApi: LocalStorageApi = {\n get: (key) => localKvStore.get(key),\n set: (key, value) => localKvStore.set(key, value),\n getJSON: <T>(key: string) => localKvStore.getJSON<T>(key),\n setJSON: <T>(key: string, value: T) => localKvStore.setJSON(key, value),\n remove: (key) => localKvStore.remove(key),\n clear: async () => {\n // LocalKvStore doesn't have clear - this is a no-op\n log.debug(\"clear() is not supported in container storage mode\");\n },\n };\n\n // Create wallet API adapter\n const walletApi = createWalletApi(signerManager);\n\n // Create chain API\n const chainApi: ChainApi = {\n getClient(descriptor) {\n log.debug(\"getClient called\", { genesis: descriptor.genesis });\n const client = getClient(descriptor);\n return client.getTypedApi(descriptor);\n },\n\n getRawClient(descriptor) {\n log.debug(\"getRawClient called\", { genesis: descriptor.genesis });\n return getClient(descriptor);\n },\n\n async connect<T extends Record<string, ChainDefinition>>(chains: T) {\n log.debug(\"connect called\", { chains: Object.keys(chains) });\n return createChainClient({ chains });\n },\n\n isConnected(descriptor) {\n return isConnected(descriptor);\n },\n\n destroyAll() {\n log.debug(\"destroyAll called\");\n destroyAll();\n },\n };\n\n // Create Cloud Storage API adapter (null if disabled)\n const cloudStorageApi: CloudStorageApi | null = cloudStorageClient\n ? {\n upload: async (data) => {\n const bytes = typeof data === \"string\" ? new TextEncoder().encode(data) : data;\n try {\n // Explicitly request a DAG-PB manifest so chunked uploads always\n // resolve to a single root CID. Without this, AsyncBulletinClient\n // can return `result.cid: undefined` for chunked-without-manifest\n // uploads — but app consumers expect a CID they can hand to\n // `fetch(cid)`, so treat a missing CID as an error.\n const uploaded = await cloudStorageClient\n .store(bytes)\n .withManifest(true)\n .send();\n if (!uploaded.cid) {\n return err(\n new ProductCloudStorageError(\n \"Cloud storage upload returned no CID despite .withManifest(true). Upstream contract may have shifted — file an issue.\",\n ),\n );\n }\n return ok(uploaded.cid.toString());\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n return err(new ProductCloudStorageError(message, { cause }));\n }\n },\n fetch: (cid) => cloudStorageClient.fetchBytes(cid),\n computeCid: async (data) => {\n const bytes = typeof data === \"string\" ? new TextEncoder().encode(data) : data;\n const cid = await calculateCid(bytes);\n return cid.toString();\n },\n }\n : null;\n\n log.info(\"Product SDK app created\", {\n name: config.name,\n cloudStorage: cloudStorageEnabled ? cloudStorageEnvironment : \"disabled\",\n });\n\n return {\n wallet: walletApi,\n localStorage: localStorageApi,\n chain: chainApi,\n cloudStorage: cloudStorageApi,\n getAppInfo: () => ({ ...config }),\n };\n}\n\n/**\n * Create wallet API adapter using SignerManager from leaf package\n */\nfunction createWalletApi(signerManager: SignerManager): WalletApi {\n // Track account change subscribers\n const accountChangeSubscribers = new Set<(account: Account | null) => void>();\n\n // Subscribe to signer manager state changes\n signerManager.subscribe((state) => {\n const account = state.selectedAccount\n ? {\n address: state.selectedAccount.address,\n name: state.selectedAccount.name ?? undefined,\n source: state.selectedAccount.source,\n }\n : null;\n for (const callback of accountChangeSubscribers) {\n try {\n callback(account);\n } catch (e) {\n log.warn(\"Account change callback threw\", { error: e });\n }\n }\n });\n\n return {\n async connect(): Promise<{ accounts: Account[] }> {\n const result = await signerManager.connect();\n if (!result.ok) {\n throw new Error(result.error.message);\n }\n return {\n accounts: result.value.map((a) => ({\n address: a.address,\n name: a.name ?? undefined,\n source: a.source,\n })),\n };\n },\n\n async disconnect(): Promise<void> {\n signerManager.disconnect();\n },\n\n getAccounts(): Account[] {\n return signerManager.getState().accounts.map((a) => ({\n address: a.address,\n name: a.name ?? undefined,\n source: a.source,\n }));\n },\n\n getSelectedAccount(): Account | null {\n const selected = signerManager.getState().selectedAccount;\n if (!selected) return null;\n return {\n address: selected.address,\n name: selected.name ?? undefined,\n source: selected.source,\n };\n },\n\n selectAccount(address: string): void {\n signerManager.selectAccount(address);\n },\n\n async signMessage(message: string | Uint8Array): Promise<Uint8Array> {\n const bytes = typeof message === \"string\" ? new TextEncoder().encode(message) : message;\n const result = await signerManager.signRaw(bytes);\n if (!result.ok) {\n throw new Error(result.error.message);\n }\n return result.value;\n },\n\n async signMessageWithDotNsIdentity(args) {\n const message =\n typeof args.message === \"string\"\n ? new TextEncoder().encode(args.message)\n : args.message;\n const accountsProvider = await getHostAccountsProvider();\n const username = args.username ?? (await getPrimaryUsername(accountsProvider));\n\n // Reuse an already-connected People chain when the caller has\n // wired one up via `app.chain.connect({ ..., <name>: peopleChain })`.\n // Fall back to opening a transient connection so first-time users\n // don't have to think about chain lifecycles. The chain-client\n // module caches by genesis fingerprint, so subsequent\n // signMessageWithDotNsIdentity calls share whichever connection\n // got established first.\n const peopleClient = isConnected(args.peopleChain)\n ? getClient(args.peopleChain)\n : await createChainClient({ chains: { people: args.peopleChain } }).then(\n (c) => c.raw.people,\n );\n // PAPI's `TypedApi.query.X.Y.getValue` is variadic\n // (`...args: [...WithCallOptions<Args>]`) so it's not assignable\n // to our deliberately-narrow `(key) => Promise<...>` shape. The\n // resolver only ever passes the storage key; the cast adapts the\n // wider PAPI surface to the minimum we depend on.\n const peopleApi = peopleClient.getTypedApi(\n args.peopleChain,\n ) as unknown as PeopleUsernameQueryApi;\n const owner = await resolvePeopleUsernameOwner(username, peopleApi);\n if (!owner) {\n throw new Error(`No account owns DotNS username \"${username}\"`);\n }\n\n const publicKey = accountIdBytes(owner);\n // This field is hex, not the SS58 the resolver now returns. Converted\n // here and not in the try, so an address failure is not reported as a\n // signing failure.\n const accountId = accountIdBytesToHex(publicKey);\n const signer = accountsProvider.getLegacyAccountSigner({ publicKey, name: username });\n\n try {\n return {\n username,\n accountId,\n signature: await signer.signBytes(message),\n };\n } catch (cause) {\n throw new Error(\n `Failed to sign with DotNS username \"${username}\": ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\n { cause },\n );\n }\n },\n\n onAccountChange(callback: (account: Account | null) => void): () => void {\n accountChangeSubscribers.add(callback);\n return () => accountChangeSubscribers.delete(callback);\n },\n\n getProductAccount(): Account | null {\n // Product accounts require async call - this sync API can't support it properly\n // Users should use SignerManager.getProductAccount() directly\n log.warn(\n \"getProductAccount() is deprecated - use SignerManager.getProductAccount() directly\",\n );\n return null;\n },\n\n getAnonymousAlias(): string | null {\n // Anonymous aliases require async call - this sync API can't support it properly\n // Users should use SignerManager.getProductAccountAlias() directly\n log.warn(\n \"getAnonymousAlias() is deprecated - use SignerManager.getProductAccountAlias() directly\",\n );\n return null;\n },\n\n async createProof(_message: Uint8Array): Promise<Uint8Array> {\n // Ring VRF proofs require SignerManager.createRingVRFProof() directly\n throw new Error(\n \"createProof() is not implemented in the App API. \" +\n \"Use SignerManager.createRingVRFProof() directly.\",\n );\n },\n };\n}\n\ntype HostAccountsProvider = NonNullable<Awaited<ReturnType<typeof getAccountsProvider>>>;\n\nasync function getHostAccountsProvider(): Promise<HostAccountsProvider> {\n const provider = await getAccountsProvider();\n if (!provider) {\n throw new Error(\"Host accounts provider is not available\");\n }\n return provider;\n}\n\nasync function getPrimaryUsername(accountsProvider: HostAccountsProvider): Promise<string> {\n const result = await accountsProvider.getUserId().match(\n (value) => value,\n (err) => {\n throw err;\n },\n );\n const username = result.primaryUsername.trim();\n if (!username) {\n throw new Error(\"Host identity did not provide a primary DotNS username\");\n }\n return username;\n}\n"]}
@@ -1,130 +0,0 @@
1
- // Copyright 2026 Parity Technologies (UK) Ltd.
2
- // SPDX-License-Identifier: Apache-2.0
3
- /**
4
- * Frozen vectors for the deprecated context-alias helpers.
5
- *
6
- * These pin current behaviour so the deprecation cannot silently alter the
7
- * derivation. Never re-derive: a caller may use the value as a plain
8
- * identifier, where different output bytes would be a silent break.
9
- */
10
- import { ss58Decode, ss58Encode } from "@parity/product-sdk-address";
11
- import { blake2b256 } from "@parity/product-sdk-crypto";
12
- import { describe, expect, it } from "vitest";
13
- import * as identity from "./index.js";
14
- import { deriveContextAlias, verifyContextAlias } from "./product-account.js";
15
-
16
- const ALICE = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY";
17
- const CONTEXT = "voting-round-1";
18
-
19
- /** Recomputes the documented formula from primitives, independent of the implementation. */
20
- function expectedAliasPublicKey(parentAddress: string, context: string): Uint8Array {
21
- const { publicKey } = ss58Decode(parentAddress);
22
- const contextBytes = new TextEncoder().encode(context);
23
- const combined = new Uint8Array(publicKey.length + contextBytes.length);
24
- combined.set(publicKey, 0);
25
- combined.set(contextBytes, publicKey.length);
26
- return blake2b256(combined);
27
- }
28
-
29
- describe("deriveContextAlias", () => {
30
- it("returns blake2b256(parentPublicKey || context), encoded at the given prefix", () => {
31
- const alias = deriveContextAlias(ALICE, CONTEXT);
32
- const expected = expectedAliasPublicKey(ALICE, CONTEXT);
33
-
34
- expect(alias.address).toBe(ss58Encode(expected, 42));
35
- });
36
-
37
- it("matches a frozen vector for a known parent and context", () => {
38
- const alias = deriveContextAlias(ALICE, CONTEXT);
39
-
40
- expect(alias.address).toBe("5GPTdhxkG9wNKhCSN1vZrCwrf3fwvAf4j487vqrkVzvRMH6F");
41
- expect(alias.h160Address).toBe("0x93d10a91de267ba79b27fbec373e5a3b2e86a283");
42
- expect(alias.parentAddress).toBe(ALICE);
43
- expect(alias.context).toBe(CONTEXT);
44
- });
45
-
46
- it("defaults to ss58 prefix 42", () => {
47
- expect(deriveContextAlias(ALICE, CONTEXT).address).toBe(
48
- deriveContextAlias(ALICE, CONTEXT, 42).address,
49
- );
50
- });
51
-
52
- it("changes only the encoding when the ss58 prefix changes, not the key", () => {
53
- const at42 = deriveContextAlias(ALICE, CONTEXT, 42);
54
- const at0 = deriveContextAlias(ALICE, CONTEXT, 0);
55
-
56
- expect(at0.address).not.toBe(at42.address);
57
- expect(Array.from(ss58Decode(at0.address).publicKey)).toEqual(
58
- Array.from(ss58Decode(at42.address).publicKey),
59
- );
60
- });
61
-
62
- it("derives a different alias for a different context", () => {
63
- expect(deriveContextAlias(ALICE, "round-1").address).not.toBe(
64
- deriveContextAlias(ALICE, "round-2").address,
65
- );
66
- });
67
- });
68
-
69
- describe("verifyContextAlias", () => {
70
- it("accepts an alias derived from the same parent and context", () => {
71
- const alias = deriveContextAlias(ALICE, CONTEXT);
72
-
73
- expect(verifyContextAlias(alias.address, ALICE, CONTEXT)).toBe(true);
74
- });
75
-
76
- it("rejects a different context", () => {
77
- const alias = deriveContextAlias(ALICE, CONTEXT);
78
-
79
- expect(verifyContextAlias(alias.address, ALICE, "voting-round-2")).toBe(false);
80
- });
81
-
82
- it("rejects a different parent", () => {
83
- const alias = deriveContextAlias(ALICE, CONTEXT);
84
- const bob = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty";
85
-
86
- expect(verifyContextAlias(alias.address, bob, CONTEXT)).toBe(false);
87
- });
88
-
89
- it("returns false rather than throwing on an undecodable address", () => {
90
- expect(verifyContextAlias("not-an-address", ALICE, CONTEXT)).toBe(false);
91
- });
92
-
93
- // Guards the byte-level comparison: `addressesEqual` from
94
- // @parity/product-sdk-address compares SS58 strings exactly and would
95
- // return false here, silently narrowing behaviour.
96
- it("compares public keys, so it accepts an alias encoded at another prefix", () => {
97
- const alias = deriveContextAlias(ALICE, CONTEXT, 42);
98
- const reencoded = ss58Encode(ss58Decode(alias.address).publicKey, 0);
99
-
100
- expect(reencoded).not.toBe(alias.address);
101
- expect(verifyContextAlias(reencoded, ALICE, CONTEXT)).toBe(true);
102
- });
103
- });
104
-
105
- describe("the identity export surface", () => {
106
- // These threw on every call, so no working consumer could exist. Deleting
107
- // turns a guaranteed runtime throw into a compile error.
108
- it("no longer exports the unimplemented ring helpers", () => {
109
- for (const name of ["deriveAnonymousAlias", "createRingProof", "verifyRingProof"]) {
110
- expect(name in identity).toBe(false);
111
- }
112
- });
113
-
114
- it("still exports the DotNS helpers and the deprecated context-alias pair", () => {
115
- for (const name of [
116
- "resolveDotNs",
117
- "reverseDotNs",
118
- "isDotNsAvailable",
119
- "resolvePeopleUsernameOwner",
120
- "isValidDotNsName",
121
- "normalizeDotNsName",
122
- "accountIdHexToBytes",
123
- "accountIdToHex",
124
- "deriveContextAlias",
125
- "verifyContextAlias",
126
- ]) {
127
- expect(name in identity).toBe(true);
128
- }
129
- });
130
- });
@@ -1,115 +0,0 @@
1
- // Copyright 2026 Parity Technologies (UK) Ltd.
2
- // SPDX-License-Identifier: Apache-2.0
3
- /**
4
- * Context alias derivation (deprecated, removal in 0.23.0)
5
- *
6
- * Derives a deterministic, context-bound alias from a parent account using blake2b-256.
7
- *
8
- * The output is a hash, not a key, so no signing key exists for the addresses
9
- * returned here. See the notes on each function for what to use instead.
10
- *
11
- * NOTE: this is NOT the canonical sr25519 product-account derivation used by
12
- * mobile, desktop, and dotli hosts. For that, use
13
- * `@parity/product-sdk-keys::deriveProductAccountPublicKey`.
14
- */
15
-
16
- import { createLogger } from "@parity/product-sdk-logger";
17
- import { blake2b256 } from "@parity/product-sdk-crypto";
18
- import { ss58Encode, ss58Decode, deriveH160 } from "@parity/product-sdk-address";
19
- import type { ContextAliasInfo } from "./types.js";
20
-
21
- const log = createLogger("identity");
22
-
23
- /**
24
- * Derive a context-bound alias from a parent account.
25
- *
26
- * The alias is deterministically derived using:
27
- * aliasPublicKey = blake2b256(parentPublicKey || context)
28
- *
29
- * @deprecated Returns addresses that no key can spend. The alias public key is a
30
- * blake2b-256 hash rather than a derived key, so no secret corresponds to the
31
- * SS58 address or to the H160: both can receive value and neither can ever
32
- * send it. Removal: `@parity/product-sdk` 0.23.0. Replace by intent:
33
- *
34
- * - An account that holds or spends value:
35
- * `SignerManager.getProductAccount(dotNsIdentifier, index)` from
36
- * `@parity/product-sdk-signer`. Host-backed and actually signable.
37
- * - The address offline, with no host: `deriveProductAccountPublicKey` from
38
- * `@parity/product-sdk-keys`, the canonical sr25519 soft derivation.
39
- * - An unlinkable per-context alias: select a registered ring-VRF key, then call
40
- * `SignerManager.getProductAccountAlias(keyHandle, context, location)` or
41
- * `createRingVRFProof(keyHandle, context, location, message)`.
42
- * - A context-scoped identifier, never used as an account: `blake2b256` from
43
- * `@parity/product-sdk/crypto`. Same bytes, without address packaging that
44
- * invites the mistake.
45
- *
46
- * @param parentAddress - Parent account SS58 address
47
- * @param context - Context string for derivation (e.g. an app id or scope label)
48
- * @param ss58Prefix - SS58 prefix (default: 42)
49
- * @returns Context alias info
50
- */
51
- export function deriveContextAlias(
52
- parentAddress: string,
53
- context: string,
54
- ss58Prefix = 42,
55
- ): ContextAliasInfo {
56
- const { publicKey: parentPublicKey } = ss58Decode(parentAddress);
57
-
58
- // Derive alias public key: blake2b-256(parentPublicKey || context)
59
- const contextBytes = new TextEncoder().encode(context);
60
- const combined = new Uint8Array(parentPublicKey.length + contextBytes.length);
61
- combined.set(parentPublicKey, 0);
62
- combined.set(contextBytes, parentPublicKey.length);
63
-
64
- const aliasPublicKey = blake2b256(combined);
65
- const address = ss58Encode(aliasPublicKey, ss58Prefix);
66
- const h160Address = deriveH160(aliasPublicKey);
67
-
68
- log.debug("Derived context alias", {
69
- parentAddress,
70
- context,
71
- address,
72
- });
73
-
74
- return {
75
- address,
76
- h160Address,
77
- parentAddress,
78
- context,
79
- };
80
- }
81
-
82
- /**
83
- * Verify that a context alias was derived from a parent account.
84
- *
85
- * @deprecated Recomputes {@link deriveContextAlias} from two public values and
86
- * compares the result, so it confirms a derivation relationship and nothing
87
- * more. No secret enters the operation at any point, which means there is
88
- * nothing here to authenticate: a passing result does not show that anyone
89
- * controls either account. Removal: `@parity/product-sdk` 0.23.0.
90
- *
91
- * @param aliasAddress - Context alias SS58 address
92
- * @param parentAddress - Claimed parent address
93
- * @param context - Context string used for derivation
94
- * @returns True if derivation is valid
95
- */
96
- export function verifyContextAlias(
97
- aliasAddress: string,
98
- parentAddress: string,
99
- context: string,
100
- ): boolean {
101
- try {
102
- const derived = deriveContextAlias(parentAddress, context);
103
- const { publicKey: aliasKey } = ss58Decode(aliasAddress);
104
- const { publicKey: derivedKey } = ss58Decode(derived.address);
105
-
106
- // Compare public keys
107
- if (aliasKey.length !== derivedKey.length) return false;
108
- for (let i = 0; i < aliasKey.length; i++) {
109
- if (aliasKey[i] !== derivedKey[i]) return false;
110
- }
111
- return true;
112
- } catch {
113
- return false;
114
- }
115
- }