@unicitylabs/sphere-sdk 0.10.6 → 0.10.7

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 (37) hide show
  1. package/dist/connect/index.cjs +1 -1
  2. package/dist/connect/index.cjs.map +1 -1
  3. package/dist/connect/index.js +1 -1
  4. package/dist/connect/index.js.map +1 -1
  5. package/dist/impl/browser/connect/index.cjs +1 -1
  6. package/dist/impl/browser/connect/index.cjs.map +1 -1
  7. package/dist/impl/browser/connect/index.js +1 -1
  8. package/dist/impl/browser/connect/index.js.map +1 -1
  9. package/dist/impl/browser/index.cjs +24 -3
  10. package/dist/impl/browser/index.cjs.map +1 -1
  11. package/dist/impl/browser/index.js +24 -3
  12. package/dist/impl/browser/index.js.map +1 -1
  13. package/dist/impl/nodejs/index.cjs +24 -3
  14. package/dist/impl/nodejs/index.cjs.map +1 -1
  15. package/dist/impl/nodejs/index.d.cts +9 -1
  16. package/dist/impl/nodejs/index.d.ts +9 -1
  17. package/dist/impl/nodejs/index.js +24 -3
  18. package/dist/impl/nodejs/index.js.map +1 -1
  19. package/dist/impl/shared/wallet-api/index.cjs +24 -3
  20. package/dist/impl/shared/wallet-api/index.cjs.map +1 -1
  21. package/dist/impl/shared/wallet-api/index.d.cts +9 -1
  22. package/dist/impl/shared/wallet-api/index.d.ts +9 -1
  23. package/dist/impl/shared/wallet-api/index.js +24 -3
  24. package/dist/impl/shared/wallet-api/index.js.map +1 -1
  25. package/dist/index.cjs +24 -3
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +9 -1
  28. package/dist/index.d.ts +9 -1
  29. package/dist/index.js +24 -3
  30. package/dist/index.js.map +1 -1
  31. package/dist/wallet-api/index.cjs +24 -3
  32. package/dist/wallet-api/index.cjs.map +1 -1
  33. package/dist/wallet-api/index.d.cts +9 -1
  34. package/dist/wallet-api/index.d.ts +9 -1
  35. package/dist/wallet-api/index.js +24 -3
  36. package/dist/wallet-api/index.js.map +1 -1
  37. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../node_modules/@noble/hashes/src/utils.ts","../../node_modules/@noble/hashes/src/_md.ts","../../node_modules/@noble/hashes/src/sha2.ts","../../core/crypto.ts","../../core/errors.ts","../../wallet-api/errors.ts","../../wallet-api/challenge.ts","../../wallet-api/codec.ts","../../wallet-api/wake-supervisor.ts","../../wallet-api/client.ts"],"sourcesContent":["/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n: number, title: string = ''): void {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(\n value: TArg<Uint8Array>,\n length?: number,\n title: string = ''\n): TRet<Uint8Array> {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet<Uint8Array>;\n}\n\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h: TArg<CHash>): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1) throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\n\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr: TArg<TypedArray>): TRet<Uint8Array> {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet<Uint8Array>;\n}\n\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr: TArg<TypedArray>): TRet<Uint32Array> {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet<Uint32Array>;\n}\n\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays: TArg<TypedArray[]>): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg<TypedArray>): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr: TArg<Uint32Array>): TRet<Uint32Array> {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr as TRet<Uint32Array>;\n}\n\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array> = isLE\n ? (u: TArg<Uint32Array>) => u as TRet<Uint32Array>\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg<Uint8Array>): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet<Uint8Array> {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet<Uint8Array> {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data: TArg<KDFInput>, errorTitle = ''): TRet<Uint8Array> {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<Uint8Array> {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash<T> {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by `digest()`. */\n outputLen: number;\n /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n canXOF: boolean;\n /**\n * Absorbs more message bytes into the running hash state.\n * @param buf - message chunk to absorb\n * @returns The same hash instance for chaining.\n */\n update(buf: TArg<Uint8Array>): this;\n /**\n * Finalizes the hash into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg<Uint8Array>): void;\n /**\n * Finalizes the hash and returns a freshly allocated digest.\n * @returns Digest bytes.\n */\n digest(): TRet<Uint8Array>;\n /** Wipes internal state and makes the instance unusable. */\n destroy(): void;\n /**\n * Copies the current hash state into an existing or new instance.\n * @param to - Optional destination instance to reuse.\n * @returns Cloned hash state.\n */\n _cloneInto(to?: T): T;\n /**\n * Creates an independent copy of the current hash state.\n * @returns Cloned hash instance.\n */\n clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n /**\n * Mixes more entropy into the generator state.\n * @param seed - fresh entropy bytes\n * @returns Nothing. Implementations update internal state in place.\n */\n addEntropy(seed: TArg<Uint8Array>): void;\n /**\n * Generates pseudorandom output bytes.\n * @param length - number of bytes to generate\n * @returns Generated pseudorandom bytes.\n */\n randomBytes(length: number): TRet<Uint8Array>;\n /** Wipes generator state and makes the instance unusable. */\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n /**\n * Reads more bytes from the XOF stream.\n * @param bytes - number of bytes to read\n * @returns Requested digest bytes.\n */\n xof(bytes: number): TRet<Uint8Array>;\n /**\n * Reads more bytes from the XOF stream into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Filled output buffer.\n */\n xofInto(buf: TArg<Uint8Array>): TRet<Uint8Array>;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n /** DER-encoded object identifier bytes for the hash algorithm. */\n oid?: TRet<Uint8Array>;\n};\n/** Callable hash function type. */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n /** Digest size in bytes. */\n outputLen: number;\n /** Input block size in bytes. */\n blockLen: number;\n /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n canXOF: boolean;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: TArg<Uint8Array>): TRet<Uint8Array>;\n create(): T;\n }\n : {\n (msg: TArg<Uint8Array>, opts?: TArg<Opts>): TRet<Uint8Array>;\n create(opts?: Opts): T;\n });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n hashCons: HasherCons<T, Opts>,\n info: TArg<HashInfo> = {}\n): TRet<CHash<T, Opts>> {\n const hashC: any = (msg: TArg<Uint8Array>, opts?: TArg<Opts>) =>\n hashCons(opts as Opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC) as TRet<CHash<T, Opts>>;\n}\n\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet<Uint8Array> {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix: number): TRet<Required<HashInfo>> => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n abytes,\n aexists,\n aoutput,\n clean,\n createView,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport abstract class HashMD<T extends HashMD<T>> implements Hash<T> {\n // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n // when it can process whole blocks without buffering first.\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly canXOF = false;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: TArg<Uint8Array>): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: TArg<Uint8Array>): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): TRet<Uint8Array> {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet<Uint8Array>;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet<CHash<_SHA256>> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet<CHash<_SHA224>> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet<CHash<_SHA512>> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet<CHash<_SHA384>> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet<CHash<_SHA512_256>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet<CHash<_SHA512_224>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Cryptographic utilities for SDK2\n *\n * Provides BIP39 mnemonic and BIP32 key derivation functions.\n * Platform-independent - no browser-specific APIs.\n */\n\nimport * as bip39 from 'bip39';\nimport CryptoJS from 'crypto-js';\nimport elliptic from 'elliptic';\nimport { SphereError } from './errors';\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst ec = new elliptic.ec('secp256k1');\n\n/** secp256k1 curve order */\nconst CURVE_ORDER = BigInt(\n '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141'\n);\n\n/** Default derivation path for Unicity (BIP44) */\nexport const DEFAULT_DERIVATION_PATH = \"m/44'/0'/0'\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface MasterKey {\n privateKey: string;\n chainCode: string;\n}\n\nexport interface DerivedKey {\n privateKey: string;\n chainCode: string;\n}\n\nexport interface KeyPair {\n privateKey: string;\n publicKey: string;\n}\n\nexport interface AddressInfo extends KeyPair {\n path: string;\n index: number;\n}\n\n// =============================================================================\n// BIP39 Mnemonic Functions\n// =============================================================================\n\n/**\n * Generate a new BIP39 mnemonic phrase\n * @param strength - Entropy bits (128 = 12 words, 256 = 24 words)\n */\nexport function generateMnemonic(strength: 128 | 256 = 128): string {\n return bip39.generateMnemonic(strength);\n}\n\n/**\n * Validate a BIP39 mnemonic phrase\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n return bip39.validateMnemonic(mnemonic);\n}\n\n/**\n * Convert mnemonic to seed (64-byte hex string)\n * @param mnemonic - BIP39 mnemonic phrase\n * @param passphrase - Optional passphrase for additional security\n */\nexport async function mnemonicToSeed(\n mnemonic: string,\n passphrase: string = ''\n): Promise<string> {\n const seedBuffer = await bip39.mnemonicToSeed(mnemonic, passphrase);\n return Buffer.from(seedBuffer).toString('hex');\n}\n\n/**\n * Synchronous version of mnemonicToSeed\n */\nexport function mnemonicToSeedSync(\n mnemonic: string,\n passphrase: string = ''\n): string {\n const seedBuffer = bip39.mnemonicToSeedSync(mnemonic, passphrase);\n return Buffer.from(seedBuffer).toString('hex');\n}\n\n/**\n * Convert mnemonic to entropy (for recovery purposes)\n */\nexport function mnemonicToEntropy(mnemonic: string): string {\n return bip39.mnemonicToEntropy(mnemonic);\n}\n\n/**\n * Convert entropy to mnemonic\n */\nexport function entropyToMnemonic(entropy: string): string {\n return bip39.entropyToMnemonic(entropy);\n}\n\n// =============================================================================\n// BIP32 Key Derivation\n// =============================================================================\n\n/**\n * Generate master key from seed (BIP32 standard)\n * Uses HMAC-SHA512 with key \"Bitcoin seed\"\n */\nexport function generateMasterKey(seedHex: string): MasterKey {\n const I = CryptoJS.HmacSHA512(\n CryptoJS.enc.Hex.parse(seedHex),\n CryptoJS.enc.Utf8.parse('Bitcoin seed')\n ).toString();\n\n const IL = I.substring(0, 64); // Left 32 bytes - master private key\n const IR = I.substring(64); // Right 32 bytes - master chain code\n\n // Validate master key\n const masterKeyBigInt = BigInt('0x' + IL);\n if (masterKeyBigInt === 0n || masterKeyBigInt >= CURVE_ORDER) {\n throw new SphereError('Invalid master key generated', 'VALIDATION_ERROR');\n }\n\n return {\n privateKey: IL,\n chainCode: IR,\n };\n}\n\n/**\n * Derive child key using BIP32 standard\n * @param parentPrivKey - Parent private key (64 hex chars)\n * @param parentChainCode - Parent chain code (64 hex chars)\n * @param index - Child index (>= 0x80000000 for hardened)\n */\nexport function deriveChildKey(\n parentPrivKey: string,\n parentChainCode: string,\n index: number\n): DerivedKey {\n const isHardened = index >= 0x80000000;\n let data: string;\n\n if (isHardened) {\n // Hardened derivation: 0x00 || parentPrivKey || index\n const indexHex = index.toString(16).padStart(8, '0');\n data = '00' + parentPrivKey + indexHex;\n } else {\n // Non-hardened derivation: compressedPubKey || index\n const keyPair = ec.keyFromPrivate(parentPrivKey, 'hex');\n const compressedPubKey = keyPair.getPublic(true, 'hex');\n const indexHex = index.toString(16).padStart(8, '0');\n data = compressedPubKey + indexHex;\n }\n\n // HMAC-SHA512 with chain code as key\n const I = CryptoJS.HmacSHA512(\n CryptoJS.enc.Hex.parse(data),\n CryptoJS.enc.Hex.parse(parentChainCode)\n ).toString();\n\n const IL = I.substring(0, 64); // Left 32 bytes\n const IR = I.substring(64); // Right 32 bytes (new chain code)\n\n // Add IL to parent key mod n (curve order)\n const ilBigInt = BigInt('0x' + IL);\n const parentKeyBigInt = BigInt('0x' + parentPrivKey);\n\n // Check IL is valid (less than curve order)\n if (ilBigInt >= CURVE_ORDER) {\n throw new SphereError('Invalid key: IL >= curve order', 'VALIDATION_ERROR');\n }\n\n const childKeyBigInt = (ilBigInt + parentKeyBigInt) % CURVE_ORDER;\n\n // Check child key is valid (not zero)\n if (childKeyBigInt === 0n) {\n throw new SphereError('Invalid key: child key is zero', 'VALIDATION_ERROR');\n }\n\n const childPrivKey = childKeyBigInt.toString(16).padStart(64, '0');\n\n return {\n privateKey: childPrivKey,\n chainCode: IR,\n };\n}\n\n/**\n * Derive key at a full BIP32/BIP44 path\n * @param masterPrivKey - Master private key\n * @param masterChainCode - Master chain code\n * @param path - BIP44 path like \"m/44'/0'/0'/0/0\"\n */\nexport function deriveKeyAtPath(\n masterPrivKey: string,\n masterChainCode: string,\n path: string\n): DerivedKey {\n const pathParts = path.replace('m/', '').split('/');\n\n let currentKey = masterPrivKey;\n let currentChainCode = masterChainCode;\n\n for (const part of pathParts) {\n const isHardened = part.endsWith(\"'\") || part.endsWith('h');\n const indexStr = part.replace(/['h]$/, '');\n let index = parseInt(indexStr, 10);\n\n if (isHardened) {\n index += 0x80000000; // Add hardened offset\n }\n\n const derived = deriveChildKey(currentKey, currentChainCode, index);\n currentKey = derived.privateKey;\n currentChainCode = derived.chainCode;\n }\n\n return {\n privateKey: currentKey,\n chainCode: currentChainCode,\n };\n}\n\n// =============================================================================\n// Key Pair Operations\n// =============================================================================\n\n/**\n * Get public key from private key\n * @param privateKey - Private key as hex string\n * @param compressed - Return compressed public key (default: true)\n */\nexport function getPublicKey(privateKey: string, compressed: boolean = true): string {\n const keyPair = ec.keyFromPrivate(privateKey, 'hex');\n return keyPair.getPublic(compressed, 'hex');\n}\n\n/**\n * Create key pair from private key\n */\nexport function createKeyPair(privateKey: string): KeyPair {\n return {\n privateKey,\n publicKey: getPublicKey(privateKey),\n };\n}\n\n// =============================================================================\n// Hash Functions\n// =============================================================================\n\n/**\n * Compute SHA256 hash\n */\nexport function sha256(data: string, inputEncoding: 'hex' | 'utf8' = 'hex'): string {\n const parsed =\n inputEncoding === 'hex'\n ? CryptoJS.enc.Hex.parse(data)\n : CryptoJS.enc.Utf8.parse(data);\n return CryptoJS.SHA256(parsed).toString();\n}\n\n/**\n * Compute RIPEMD160 hash\n */\nexport function ripemd160(data: string, inputEncoding: 'hex' | 'utf8' = 'hex'): string {\n const parsed =\n inputEncoding === 'hex'\n ? CryptoJS.enc.Hex.parse(data)\n : CryptoJS.enc.Utf8.parse(data);\n return CryptoJS.RIPEMD160(parsed).toString();\n}\n\n/**\n * Compute HASH160 (SHA256 -> RIPEMD160)\n */\nexport function hash160(data: string): string {\n const sha = sha256(data, 'hex');\n return ripemd160(sha, 'hex');\n}\n\n/**\n * Compute double SHA256\n */\nexport function doubleSha256(data: string, inputEncoding: 'hex' | 'utf8' = 'hex'): string {\n const first = sha256(data, inputEncoding);\n return sha256(first, 'hex');\n}\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Convert hex string to Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n const matches = hex.match(/../g);\n if (!matches) {\n return new Uint8Array(0);\n }\n return Uint8Array.from(matches.map((x) => parseInt(x, 16)));\n}\n\n/**\n * Convert Uint8Array to hex string\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Generate random bytes as hex string\n */\nexport function randomBytes(length: number): string {\n const words = CryptoJS.lib.WordArray.random(length);\n return words.toString(CryptoJS.enc.Hex);\n}\n\n// =============================================================================\n// High-Level Functions\n// =============================================================================\n\n/**\n * Generate identity from mnemonic\n * Returns master key derived from mnemonic seed\n */\nexport async function identityFromMnemonic(\n mnemonic: string,\n passphrase: string = ''\n): Promise<MasterKey> {\n if (!validateMnemonic(mnemonic)) {\n throw new SphereError('Invalid mnemonic phrase', 'INVALID_IDENTITY');\n }\n const seedHex = await mnemonicToSeed(mnemonic, passphrase);\n return generateMasterKey(seedHex);\n}\n\n/**\n * Synchronous version of identityFromMnemonic\n */\nexport function identityFromMnemonicSync(\n mnemonic: string,\n passphrase: string = ''\n): MasterKey {\n if (!validateMnemonic(mnemonic)) {\n throw new SphereError('Invalid mnemonic phrase', 'INVALID_IDENTITY');\n }\n const seedHex = mnemonicToSeedSync(mnemonic, passphrase);\n return generateMasterKey(seedHex);\n}\n\n/**\n * Derive key info at a specific path\n * @param masterKey - Master key with privateKey and chainCode\n * @param basePath - Base derivation path (e.g., \"m/44'/0'/0'\")\n * @param index - Address index\n * @param isChange - Whether this is a change address (chain 1 vs 0)\n */\nexport function deriveAddressInfo(\n masterKey: MasterKey,\n basePath: string,\n index: number,\n isChange: boolean = false\n): AddressInfo {\n const chain = isChange ? 1 : 0;\n const fullPath = `${basePath}/${chain}/${index}`;\n\n const derived = deriveKeyAtPath(masterKey.privateKey, masterKey.chainCode, fullPath);\n const publicKey = getPublicKey(derived.privateKey);\n\n return {\n privateKey: derived.privateKey,\n publicKey,\n path: fullPath,\n index,\n };\n}\n\n/**\n * Generate full key info from private key with index and path\n */\nexport function generateAddressInfo(\n privateKey: string,\n index: number,\n path: string\n): AddressInfo {\n const publicKey = getPublicKey(privateKey);\n return {\n privateKey,\n publicKey,\n path,\n index,\n };\n}\n\n/**\n * Generate key info from master private key using HMAC-SHA512 derivation\n * This matches exactly the original index.html implementation\n * NOTE: This is NON-STANDARD derivation for legacy wallet compatibility.\n *\n * Dual-use: in `wif_hmac` derivation mode (legacy wallet import) this derives\n * the wallet's chainPubkey (used for L3 identity).\n *\n * @param masterPrivateKey - 32-byte hex private key (64 chars)\n * @param index - Address index\n */\nexport function generateAddressFromMasterKey(\n masterPrivateKey: string,\n index: number\n): AddressInfo {\n const derivationPath = `m/44'/0'/${index}'`;\n\n // HMAC-SHA512 with path as key (matching index.html exactly)\n const hmacInput = CryptoJS.enc.Hex.parse(masterPrivateKey);\n const hmacKey = CryptoJS.enc.Utf8.parse(derivationPath);\n const hmacOutput = CryptoJS.HmacSHA512(hmacInput, hmacKey).toString();\n\n // Use left 32 bytes for private key\n const childPrivateKey = hmacOutput.substring(0, 64);\n\n return generateAddressInfo(childPrivateKey, index, derivationPath);\n}\n\n// =============================================================================\n// Message Signing (secp256k1 ECDSA with recoverable signature)\n// =============================================================================\n\n/** Prefix prepended to all signed messages (Bitcoin-like signed message format) */\nexport const SIGN_MESSAGE_PREFIX = 'Sphere Signed Message:\\n';\n\n/** Encode an integer as a Bitcoin-style compact varint */\nfunction varint(n: number): Uint8Array {\n if (n < 253) return new Uint8Array([n]);\n const buf = new Uint8Array(3);\n buf[0] = 253;\n buf[1] = n & 0xff;\n buf[2] = (n >> 8) & 0xff;\n return buf;\n}\n\n/**\n * Hash a message for signing using the Bitcoin-like double-SHA256 scheme:\n * SHA256(SHA256(varint(prefix.length) + prefix + varint(msg.length) + msg))\n *\n * @returns 64-char lowercase hex hash\n */\nexport function hashSignMessage(message: string): string {\n const prefix = new TextEncoder().encode(SIGN_MESSAGE_PREFIX);\n const msg = new TextEncoder().encode(message);\n const prefixLen = varint(prefix.length);\n const msgLen = varint(msg.length);\n const full = new Uint8Array(prefixLen.length + prefix.length + msgLen.length + msg.length);\n let off = 0;\n full.set(prefixLen, off); off += prefixLen.length;\n full.set(prefix, off); off += prefix.length;\n full.set(msgLen, off); off += msgLen.length;\n full.set(msg, off);\n const hex = Array.from(full).map(b => b.toString(16).padStart(2, '0')).join('');\n const h1 = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(hex)).toString();\n return CryptoJS.SHA256(CryptoJS.enc.Hex.parse(h1)).toString();\n}\n\n/**\n * Sign a message with a secp256k1 private key.\n *\n * Returns a 130-character hex string: v (2 chars) + r (64 chars) + s (64 chars).\n * The recovery byte `v` is `31 + recoveryParam` (0-3).\n *\n * @param privateKeyHex - 64-char hex private key\n * @param message - plaintext message to sign\n */\nexport function signMessage(privateKeyHex: string, message: string): string {\n const keyPair = ec.keyFromPrivate(privateKeyHex, 'hex');\n const hashHex = hashSignMessage(message);\n const hashBytes = Buffer.from(hashHex, 'hex');\n const sig = keyPair.sign(hashBytes, { canonical: true });\n\n // Find recovery parameter\n const pub = keyPair.getPublic();\n let recoveryParam = -1;\n for (let i = 0; i < 4; i++) {\n try {\n if (ec.recoverPubKey(hashBytes, sig, i).eq(pub)) {\n recoveryParam = i;\n break;\n }\n } catch { /* try next */ }\n }\n if (recoveryParam === -1) {\n throw new SphereError('Could not find recovery parameter', 'SIGNING_ERROR');\n }\n\n const v = (31 + recoveryParam).toString(16).padStart(2, '0');\n const r = sig.r.toString('hex').padStart(64, '0');\n const s = sig.s.toString('hex').padStart(64, '0');\n return v + r + s;\n}\n\n/**\n * Verify a signed message against a compressed secp256k1 public key.\n *\n * @param message - The original plaintext message\n * @param signature - 130-char hex signature (v + r + s)\n * @param expectedPubkey - 66-char compressed public key hex\n * @returns `true` if the signature is valid and matches the expected public key\n */\nexport function verifySignedMessage(\n message: string,\n signature: string,\n expectedPubkey: string,\n): boolean {\n if (signature.length !== 130) return false;\n\n const v = parseInt(signature.slice(0, 2), 16) - 31;\n const r = signature.slice(2, 66);\n const s = signature.slice(66, 130);\n\n if (v < 0 || v > 3) return false;\n\n const hashHex = hashSignMessage(message);\n const hashBytes = Buffer.from(hashHex, 'hex');\n\n try {\n const recovered = ec.recoverPubKey(hashBytes, { r, s }, v);\n const recoveredHex = recovered.encode('hex', true); // compressed\n return recoveredHex === expectedPubkey;\n } catch {\n return false;\n }\n}\n\n/**\n * Recover the compressed secp256k1 public key from a signed message.\n *\n * Use this when the server needs to identify the signer (not just verify\n * a signature against a known pubkey). Combined with `sphere.resolve(pubkey)`\n * it gives a fully cryptographically-attributable identity for backend auth,\n * without trusting any client-supplied identifier claim.\n *\n * @param message - The plaintext that was signed\n * @param signature - 130-char hex (v + r + s) as produced by `signMessage`\n * @returns - Compressed 66-char hex pubkey\n * @throws - On malformed signature length or out-of-range recovery byte\n */\nexport function recoverPubkeyFromSignature(message: string, signature: string): string {\n if (signature.length !== 130) {\n throw new SphereError(\n `Invalid signature length: expected 130 hex chars, got ${signature.length}`,\n 'SIGNING_ERROR',\n );\n }\n\n const v = parseInt(signature.slice(0, 2), 16) - 31;\n const r = signature.slice(2, 66);\n const s = signature.slice(66, 130);\n\n if (v < 0 || v > 3) {\n throw new SphereError(\n `Invalid recovery byte: v=${v} out of range [0..3]`,\n 'SIGNING_ERROR',\n );\n }\n\n const hashHex = hashSignMessage(message);\n const hashBytes = Buffer.from(hashHex, 'hex');\n\n const recovered = ec.recoverPubKey(hashBytes, { r, s }, v);\n return recovered.encode('hex', true);\n}\n\n// Re-export elliptic instance for advanced use cases\nexport { ec };\n","/**\n * SDK Error Types\n *\n * Structured error codes for programmatic error handling in UI.\n * UI can switch on error.code to show appropriate user-facing messages.\n *\n * @example\n * ```ts\n * import { SphereError } from '@unicitylabs/sphere-sdk';\n *\n * try {\n * await sphere.payments.send({ ... });\n * } catch (err) {\n * if (err instanceof SphereError) {\n * switch (err.code) {\n * case 'INSUFFICIENT_BALANCE': showToast('Not enough funds'); break;\n * case 'INVALID_RECIPIENT': showToast('Recipient not found'); break;\n * case 'TRANSPORT_ERROR': showToast('Network connection issue'); break;\n * case 'TIMEOUT': showToast('Request timed out, try again'); break;\n * default: showToast(err.message);\n * }\n * }\n * }\n * ```\n */\n\nexport type SphereErrorCode =\n | 'NOT_INITIALIZED'\n | 'ALREADY_INITIALIZED'\n | 'INVALID_CONFIG'\n | 'INVALID_IDENTITY'\n | 'INSUFFICIENT_BALANCE'\n | 'INVALID_RECIPIENT'\n | 'TRANSFER_FAILED'\n // The source state was consumed by a DIFFERENT transaction (lost race, not a\n // resume) — raised as TransferConflictError (token-engine/errors.ts, Part E.2).\n | 'TRANSFER_CONFLICT'\n | 'STORAGE_ERROR'\n | 'TRANSPORT_ERROR'\n | 'AGGREGATOR_ERROR'\n | 'VALIDATION_ERROR'\n | 'INVALID_AMOUNT'\n | 'NETWORK_ERROR'\n | 'TIMEOUT'\n | 'DECRYPTION_ERROR'\n | 'MODULE_NOT_AVAILABLE'\n | 'SIGNING_ERROR'\n // Token Spend Queue error codes\n | 'SEND_QUEUE_TIMEOUT'\n | 'SEND_INSUFFICIENT_BALANCE'\n | 'SEND_RESERVATION_CANCELLED'\n | 'SEND_QUEUE_FULL'\n | 'MODULE_DESTROYED'\n | 'REENTRANT_GATE'\n // Invoice / Accounting error codes\n | 'INVOICE_NO_TARGETS'\n | 'INVOICE_INVALID_ADDRESS'\n | 'INVOICE_NO_ASSETS'\n | 'INVOICE_INVALID_ASSET'\n | 'INVOICE_INVALID_AMOUNT'\n | 'INVOICE_INVALID_COIN'\n | 'INVOICE_INVALID_NFT'\n | 'INVOICE_PAST_DUE_DATE'\n | 'INVOICE_DUPLICATE_ADDRESS'\n | 'INVOICE_DUPLICATE_COIN'\n | 'INVOICE_DUPLICATE_NFT'\n | 'INVOICE_MINT_FAILED'\n | 'INVOICE_INVALID_PROOF'\n | 'INVOICE_WRONG_TOKEN_TYPE'\n | 'INVOICE_INVALID_DATA'\n | 'INVOICE_ALREADY_EXISTS'\n | 'INVOICE_NOT_FOUND'\n | 'INVOICE_NOT_TARGET'\n | 'INVOICE_ALREADY_CLOSED'\n | 'INVOICE_ALREADY_CANCELLED'\n | 'INVOICE_ORACLE_REQUIRED'\n | 'INVOICE_TERMINATED'\n | 'INVOICE_INVALID_TARGET'\n | 'INVOICE_INVALID_ASSET_INDEX'\n | 'INVOICE_RETURN_EXCEEDS_BALANCE'\n | 'INVOICE_INVALID_DELIVERY_METHOD'\n | 'INVOICE_INVALID_REFUND_ADDRESS'\n | 'INVOICE_INVALID_CONTACT'\n | 'INVOICE_INVALID_ID'\n | 'INVOICE_TOO_MANY_TARGETS'\n | 'INVOICE_TOO_MANY_ASSETS'\n | 'INVOICE_MEMO_TOO_LONG'\n | 'INVOICE_TERMS_TOO_LARGE'\n | 'INVOICE_NOT_TERMINATED'\n | 'INVOICE_NOT_CANCELLED'\n | 'INVOICE_STORAGE_FAILED'\n | 'RATE_LIMITED'\n | 'COMMUNICATIONS_UNAVAILABLE'\n // Swap error codes\n | 'SWAP_INVALID_DEAL'\n | 'SWAP_INVALID_MANIFEST'\n | 'SWAP_NOT_FOUND'\n | 'SWAP_WRONG_STATE'\n | 'SWAP_RESOLVE_FAILED'\n | 'SWAP_DM_SEND_FAILED'\n | 'SWAP_ESCROW_REJECTED'\n | 'SWAP_DEPOSIT_FAILED'\n | 'SWAP_PAYOUT_VERIFICATION_FAILED'\n | 'SWAP_ALREADY_EXISTS'\n | 'SWAP_ALREADY_COMPLETED'\n | 'SWAP_ALREADY_CANCELLED'\n | 'SWAP_TIMEOUT'\n | 'SWAP_LIMIT_EXCEEDED'\n | 'SWAP_ALREADY_INITIALIZED'\n | 'SWAP_MODULE_DESTROYED'\n | 'SWAP_NOT_INITIALIZED';\n\nexport class SphereError extends Error {\n readonly code: SphereErrorCode;\n readonly cause?: unknown;\n\n constructor(message: string, code: SphereErrorCode, cause?: unknown) {\n super(message);\n this.name = 'SphereError';\n this.code = code;\n this.cause = cause;\n }\n}\n\n/**\n * Type guard to check if an error is a SphereError\n */\nexport function isSphereError(err: unknown): err is SphereError {\n return err instanceof SphereError;\n}\n","/**\n * wallet-api/errors.ts — the client's typed error surface (S1).\n *\n * HTTP error mapping follows ARCHITECTURE §16: `{ error: { code, message } }`\n * with 401 auth · 403 ownership/addressee · 404 unknown · 409 conflict\n * (lineage/ownership) · 413 too large · 422 validation · 429 rate-limit/quota.\n */\n\nexport type WalletApiErrorCode =\n /** Construction/config problems (bad base URL, missing identity). */\n | 'CONFIG'\n /** The server challenge failed template verification — never signed. */\n | 'CHALLENGE_TEMPLATE'\n /** 401 — session invalid and re-auth also failed. */\n | 'UNAUTHORIZED'\n /** 403 — ownership/addressee check failed. */\n | 'FORBIDDEN'\n /** 404 — unknown resource. */\n | 'NOT_FOUND'\n /** 409 — lineage/ownership conflict (e.g. evidenced-tombstone re-add — §5.3). */\n | 'CONFLICT'\n /** 413 — blob too large. */\n | 'TOO_LARGE'\n /** 422 — validation failure (malformed body, failed §8.2 pipeline). */\n | 'VALIDATION'\n /** 429 — rate limit / quota. */\n | 'RATE_LIMITED'\n /** Transport-level failure (fetch threw, connection refused, …). */\n | 'NETWORK'\n /** The response did not match the §16 contract (parse/shape failure). */\n | 'PROTOCOL'\n /** Any other non-2xx status. */\n | 'SERVER';\n\nconst STATUS_TO_CODE: Record<number, WalletApiErrorCode> = {\n 401: 'UNAUTHORIZED',\n 403: 'FORBIDDEN',\n 404: 'NOT_FOUND',\n 409: 'CONFLICT',\n 413: 'TOO_LARGE',\n 422: 'VALIDATION',\n 429: 'RATE_LIMITED',\n};\n\nexport class WalletApiError extends Error {\n readonly code: WalletApiErrorCode;\n /** HTTP status when the error came from a response. */\n readonly status?: number;\n\n constructor(message: string, code: WalletApiErrorCode, status?: number, cause?: unknown) {\n super(message);\n this.name = 'WalletApiError';\n this.code = code;\n this.status = status;\n if (cause !== undefined) (this as { cause?: unknown }).cause = cause;\n }\n\n static fromStatus(status: number, message: string): WalletApiError {\n return new WalletApiError(message, STATUS_TO_CODE[status] ?? 'SERVER', status);\n }\n}\n\n/**\n * The auth challenge failed template verification (S1): wrong domain prefix,\n * foreign pubkey, or implausible timestamps. The spend key never signs\n * server-chosen text that fails this check.\n */\nexport class ChallengeTemplateError extends WalletApiError {\n constructor(message: string) {\n super(message, 'CHALLENGE_TEMPLATE');\n this.name = 'ChallengeTemplateError';\n }\n}\n","/**\n * wallet-api/challenge.ts — auth-challenge template verification (S1,\n * ARCHITECTURE §4).\n *\n * The spend key NEVER signs arbitrary server-chosen text. Before signing, the\n * client verifies the challenge:\n * 1. begins with the fixed domain-separation prefix\n * `unicity:wallet-api:auth:v1\\n`;\n * 2. embeds the client's OWN pubkey (and the nonce returned alongside it);\n * 3. carries plausible timestamps (`issuedAt` near now, `expiresAt` in the\n * future, a sane validity window).\n *\n * The accepted grammar matches the REAL backend (wallet-api M1,\n * src/auth/service.ts): the prefix followed by a single-line JSON object with\n * `network`, `pubkey`, `nonce`, `issuedAt`, `expiresAt` (ISO-8601). This\n * grammar is the client's acceptance contract: a server whose challenge does\n * not parse is refused, by design. The fake server\n * (tests/support/fake-wallet-api.ts) produces exactly this form.\n */\n\nimport { ChallengeTemplateError } from './errors';\n\n/** Fixed domain-separation prefix (ARCHITECTURE §4 step 1). */\nexport const AUTH_CHALLENGE_PREFIX = 'unicity:wallet-api:auth:v1\\n';\n\n/** Allowed clock skew between client and server (ms). */\nconst MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;\n\n/** Maximum plausible challenge validity window (server default: NONCE_TTL = 5 min). */\nconst MAX_VALIDITY_WINDOW_MS = 60 * 60 * 1000;\n\nexport interface ChallengeExpectation {\n /** The client's own compressed pubkey hex — the challenge MUST embed it. */\n pubkey: string;\n /** The nonce returned by `POST /v1/auth/challenge` alongside the challenge. */\n nonce: string;\n /** The client's network — refused if the challenge names a different one. */\n network: string;\n /** Current time, ms since epoch. */\n nowMs: number;\n}\n\nfunction parseFields(body: string): Map<string, string> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n throw new ChallengeTemplateError('Challenge body is not the single-line JSON object the backend emits');\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new ChallengeTemplateError('Challenge body must be a JSON object');\n }\n const fields = new Map<string, string>();\n for (const [key, value] of Object.entries(parsed)) {\n if (typeof value !== 'string') {\n throw new ChallengeTemplateError(`Challenge field \"${key}\" must be a string`);\n }\n fields.set(key, value);\n }\n return fields;\n}\n\nfunction requireField(fields: Map<string, string>, key: string): string {\n const value = fields.get(key);\n if (value === undefined || value === '') {\n throw new ChallengeTemplateError(`Challenge is missing the \"${key}\" field`);\n }\n return value;\n}\n\nfunction parseTimestamp(value: string, key: string): number {\n const ms = Date.parse(value);\n if (Number.isNaN(ms)) {\n throw new ChallengeTemplateError(`Challenge \"${key}\" is not a parseable timestamp: ${value}`);\n }\n return ms;\n}\n\n/**\n * Verify a server auth challenge before signing. Throws\n * {@link ChallengeTemplateError} on ANY violation — the caller MUST refuse to\n * sign in that case.\n */\nexport function verifyChallengeTemplate(challenge: string, expect: ChallengeExpectation): void {\n if (typeof challenge !== 'string' || !challenge.startsWith(AUTH_CHALLENGE_PREFIX)) {\n throw new ChallengeTemplateError('Challenge does not start with the unicity:wallet-api:auth:v1 domain prefix');\n }\n const fields = parseFields(challenge.slice(AUTH_CHALLENGE_PREFIX.length));\n\n const pubkey = requireField(fields, 'pubkey');\n if (pubkey.toLowerCase() !== expect.pubkey.toLowerCase()) {\n throw new ChallengeTemplateError('Challenge embeds a different pubkey than this wallet');\n }\n\n const nonce = requireField(fields, 'nonce');\n if (nonce !== expect.nonce) {\n throw new ChallengeTemplateError('Challenge nonce does not match the nonce issued with it');\n }\n\n const network = requireField(fields, 'network');\n if (network !== expect.network) {\n throw new ChallengeTemplateError(`Challenge is for network \"${network}\", expected \"${expect.network}\"`);\n }\n\n const issuedAt = parseTimestamp(requireField(fields, 'issuedAt'), 'issuedAt');\n const expiresAt = parseTimestamp(requireField(fields, 'expiresAt'), 'expiresAt');\n\n if (issuedAt > expect.nowMs + MAX_CLOCK_SKEW_MS) {\n throw new ChallengeTemplateError('Challenge issuedAt is in the future');\n }\n if (expiresAt <= expect.nowMs - MAX_CLOCK_SKEW_MS) {\n throw new ChallengeTemplateError('Challenge is already expired');\n }\n if (expiresAt <= issuedAt || expiresAt - issuedAt > MAX_VALIDITY_WINDOW_MS) {\n throw new ChallengeTemplateError('Challenge validity window is implausible');\n }\n}\n","/**\n * wallet-api/codec.ts — runtime wire ⇄ domain conversion for §16 responses.\n *\n * Hand-rolled validators (repo convention — no zod dependency). The hard rule\n * (ARCHITECTURE §11): asset amounts are decimal strings on the wire and\n * `bigint` in domain types — never a JS `number` (they exceed 2^53). Cursors,\n * seqs and the syncEpoch are parsed the same way; the codec tolerates either\n * a decimal string (the Postgres `bigint`-over-`pg` wire form) or a safe\n * integer number for those counters, but amounts MUST be strings.\n */\n\nimport type { InventoryItem } from '../storage/storage-provider';\nimport { WalletApiError } from './errors';\nimport type {\n BlobUrlEntry,\n CoinBalance,\n HistoryPage,\n HistoryWireRecord,\n IntentRecord,\n InventoryPage,\n MailboxClaimResult,\n MailboxEntry,\n MailboxPage,\n PaymentRequestRecord,\n PaymentRequestsPage,\n UploadUrlEntry,\n} from './types';\n\nfunction protocolError(message: string): WalletApiError {\n return new WalletApiError(message, 'PROTOCOL');\n}\n\nfunction asRecord(value: unknown, what: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw protocolError(`${what} is not an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction asArray(value: unknown, what: string): unknown[] {\n if (!Array.isArray(value)) throw protocolError(`${what} is not an array`);\n return value;\n}\n\nfunction asString(value: unknown, what: string): string {\n if (typeof value !== 'string') throw protocolError(`${what} is not a string`);\n return value;\n}\n\n/** Counter (cursor/seq/syncEpoch): decimal string or safe integer → bigint. */\nexport function parseCounter(value: unknown, what: string): bigint {\n if (typeof value === 'string' && /^[0-9]+$/.test(value)) return BigInt(value);\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return BigInt(value);\n throw protocolError(`${what} is not a non-negative integer counter`);\n}\n\n/** Amount: decimal string ONLY (§11) → bigint. */\nexport function parseAmount(value: unknown, what: string): bigint {\n if (typeof value === 'string' && /^[0-9]+$/.test(value)) return BigInt(value);\n throw protocolError(`${what} is not a decimal-string amount`);\n}\n\nfunction parseAssets(value: unknown, what: string): InventoryItem['assets'] {\n if (value === undefined || value === null) return undefined;\n return asArray(value, what).map((raw, i) => {\n const rec = asRecord(raw, `${what}[${i}]`);\n return {\n coinId: asString(rec.coinId, `${what}[${i}].coinId`),\n amount: parseAmount(rec.amount, `${what}[${i}].amount`),\n };\n });\n}\n\nfunction parseInventoryItem(raw: unknown, what: string): InventoryItem {\n const rec = asRecord(raw, what);\n const status = asString(rec.status, `${what}.status`);\n if (status !== 'active' && status !== 'removed') {\n throw protocolError(`${what}.status is neither 'active' nor 'removed'`);\n }\n return {\n tokenId: asString(rec.tokenId, `${what}.tokenId`),\n status,\n assets: parseAssets(rec.assets, `${what}.assets`),\n seq: parseCounter(rec.seq, `${what}.seq`),\n };\n}\n\n/** `GET /v1/inventory` → {@link InventoryPage} (§16). */\nexport function parseInventoryPage(body: unknown): InventoryPage {\n const rec = asRecord(body, 'inventory response');\n if (typeof rec.more !== 'boolean') throw protocolError('inventory response .more is not a boolean');\n return {\n cursor: parseCounter(rec.cursor, 'inventory response .cursor'),\n syncEpoch: parseCounter(rec.syncEpoch, 'inventory response .syncEpoch'),\n more: rec.more,\n items: asArray(rec.items, 'inventory response .items').map((raw, i) =>\n parseInventoryItem(raw, `items[${i}]`)\n ),\n };\n}\n\n/** `GET /v1/balances` → {@link CoinBalance}[] (§16). */\nexport function parseBalances(body: unknown): CoinBalance[] {\n const rec = asRecord(body, 'balances response');\n return asArray(rec.balances, 'balances response .balances').map((raw, i) => {\n const b = asRecord(raw, `balances[${i}]`);\n const tokenCount = b.tokenCount;\n if (typeof tokenCount !== 'number' || !Number.isSafeInteger(tokenCount) || tokenCount < 0) {\n throw protocolError(`balances[${i}].tokenCount is not a non-negative integer`);\n }\n return {\n coinId: asString(b.coinId, `balances[${i}].coinId`),\n total: parseAmount(b.total, `balances[${i}].total`),\n tokenCount,\n };\n });\n}\n\n/** `POST /v1/tokens/blob-urls` → {@link BlobUrlEntry}[] (§16). */\nexport function parseBlobUrls(body: unknown): BlobUrlEntry[] {\n const rec = asRecord(body, 'blob-urls response');\n return asArray(rec.urls, 'blob-urls response .urls').map((raw, i) => {\n const u = asRecord(raw, `urls[${i}]`);\n return {\n tokenId: asString(u.tokenId, `urls[${i}].tokenId`),\n getUrl: asString(u.getUrl, `urls[${i}].getUrl`),\n };\n });\n}\n\n/** `POST /v1/tokens/upload-urls` → {@link UploadUrlEntry}[] (§16). */\nexport function parseUploadUrls(body: unknown): UploadUrlEntry[] {\n const rec = asRecord(body, 'upload-urls response');\n return asArray(rec.urls, 'upload-urls response .urls').map((raw, i) => {\n const u = asRecord(raw, `urls[${i}]`);\n return {\n sha256: asString(u.sha256, `urls[${i}].sha256`),\n key: asString(u.key, `urls[${i}].key`),\n putUrl: asString(u.putUrl, `urls[${i}].putUrl`),\n };\n });\n}\n\n/** `POST /v1/inventory/apply` → cursor (§16). */\nexport function parseApplyResult(body: unknown): bigint {\n const rec = asRecord(body, 'apply response');\n return parseCounter(rec.cursor, 'apply response .cursor');\n}\n\n/** `GET /v1/intents` → {@link IntentRecord}[] (§16). */\nexport function parseIntents(body: unknown): IntentRecord[] {\n const rec = asRecord(body, 'intents response');\n return asArray(rec.intents, 'intents response .intents').map((raw, i) => {\n const it = asRecord(raw, `intents[${i}]`);\n const status = asString(it.status, `intents[${i}].status`);\n if (status !== 'open' && status !== 'completed' && status !== 'aborted') {\n throw protocolError(`intents[${i}].status is not a known intent status`);\n }\n const createdAt = Date.parse(asString(it.createdAt, `intents[${i}].createdAt`));\n if (Number.isNaN(createdAt)) throw protocolError(`intents[${i}].createdAt is not a timestamp`);\n return {\n transferId: asString(it.transferId, `intents[${i}].transferId`),\n payload: asString(it.payload, `intents[${i}].payload`),\n status,\n createdAt,\n };\n });\n}\n\n// ── mailbox (§6/§16) ──────────────────────────────────────────────────────────\n\n/** `POST /v1/mailbox` → entryId (§16). */\nexport function parseDepositResult(body: unknown): string {\n const rec = asRecord(body, 'mailbox deposit response');\n return asString(rec.entryId, 'mailbox deposit response .entryId');\n}\n\nfunction parseMailboxEntry(raw: unknown, what: string): MailboxEntry {\n const rec = asRecord(raw, what);\n const status = asString(rec.status, `${what}.status`);\n if (status !== 'unclaimed' && status !== 'claimed' && status !== 'rejected') {\n throw protocolError(`${what}.status is not a known mailbox entry status`);\n }\n const createdAt = Date.parse(asString(rec.createdAt, `${what}.createdAt`));\n if (Number.isNaN(createdAt)) throw protocolError(`${what}.createdAt is not a timestamp`);\n return {\n entryId: asString(rec.entryId, `${what}.entryId`),\n seq: parseCounter(rec.seq, `${what}.seq`),\n status,\n transferId: asString(rec.transferId, `${what}.transferId`),\n tokenId: asString(rec.tokenId, `${what}.tokenId`),\n assets: (parseAssets(rec.assets, `${what}.assets`) ?? []).map((a) => ({ ...a })),\n senderPubkey: asString(rec.senderPubkey, `${what}.senderPubkey`),\n ...(rec.memo !== undefined && rec.memo !== null\n ? { memo: asString(rec.memo, `${what}.memo`) }\n : {}),\n createdAt,\n ...(rec.getUrl !== undefined && rec.getUrl !== null\n ? { getUrl: asString(rec.getUrl, `${what}.getUrl`) }\n : {}),\n ...(rec.blobCollected === true ? { blobCollected: true } : {}),\n };\n}\n\n/** `GET /v1/mailbox?since=` → {@link MailboxPage} (§16). */\nexport function parseMailboxPage(body: unknown): MailboxPage {\n const rec = asRecord(body, 'mailbox response');\n if (typeof rec.more !== 'boolean') throw protocolError('mailbox response .more is not a boolean');\n return {\n readPointer: parseCounter(rec.readPointer, 'mailbox response .readPointer'),\n syncEpoch: parseCounter(rec.syncEpoch, 'mailbox response .syncEpoch'),\n more: rec.more,\n entries: asArray(rec.entries, 'mailbox response .entries').map((raw, i) =>\n parseMailboxEntry(raw, `entries[${i}]`)\n ),\n };\n}\n\n/** `POST /v1/mailbox/claim` → {@link MailboxClaimResult} (§16). */\nexport function parseClaimResult(body: unknown): MailboxClaimResult {\n const rec = asRecord(body, 'mailbox claim response');\n return {\n claimed: asArray(rec.claimed, 'claim response .claimed').map((raw, i) =>\n asString(raw, `claimed[${i}]`)\n ),\n alreadyClaimed: asArray(rec.alreadyClaimed, 'claim response .alreadyClaimed').map((raw, i) => {\n const a = asRecord(raw, `alreadyClaimed[${i}]`);\n if (typeof a.intoInventory !== 'boolean') {\n throw protocolError(`alreadyClaimed[${i}].intoInventory is not a boolean`);\n }\n return { entryId: asString(a.entryId, `alreadyClaimed[${i}].entryId`), intoInventory: a.intoInventory };\n }),\n failed: asArray(rec.failed, 'claim response .failed').map((raw, i) => {\n const f = asRecord(raw, `failed[${i}]`);\n return { entryId: asString(f.entryId, `failed[${i}].entryId`), code: asString(f.code, `failed[${i}].code`) };\n }),\n };\n}\n\n/** `POST /v1/mailbox/reject` → rejected entry ids (§16). */\nexport function parseRejectResult(body: unknown): string[] {\n const rec = asRecord(body, 'mailbox reject response');\n return asArray(rec.rejected, 'reject response .rejected').map((raw, i) => asString(raw, `rejected[${i}]`));\n}\n\n// ── payment requests (§10/§16) ────────────────────────────────────────────────\n\n/** One §16 payment request → {@link PaymentRequestRecord} (create/respond/list). */\nexport function parsePaymentRequestRecord(raw: unknown, what: string): PaymentRequestRecord {\n const rec = asRecord(raw, what);\n const status = asString(rec.status, `${what}.status`);\n if (status !== 'open' && status !== 'paid' && status !== 'declined' && status !== 'expired') {\n throw protocolError(`${what}.status is not a known payment-request status`);\n }\n const createdAt = Date.parse(asString(rec.createdAt, `${what}.createdAt`));\n if (Number.isNaN(createdAt)) throw protocolError(`${what}.createdAt is not a timestamp`);\n let expiresAt: number | undefined;\n if (rec.expiresAt !== undefined && rec.expiresAt !== null) {\n expiresAt = Date.parse(asString(rec.expiresAt, `${what}.expiresAt`));\n if (Number.isNaN(expiresAt)) throw protocolError(`${what}.expiresAt is not a timestamp`);\n }\n if (rec.transferId !== null && typeof rec.transferId !== 'string') {\n throw protocolError(`${what}.transferId is neither a string nor null`);\n }\n return {\n id: asString(rec.id, `${what}.id`),\n seq: parseCounter(rec.seq, `${what}.seq`),\n fromPubkey: asString(rec.fromPubkey, `${what}.fromPubkey`),\n toPubkey: asString(rec.toPubkey, `${what}.toPubkey`),\n assets: (parseAssets(rec.assets, `${what}.assets`) ?? []).map((a) => ({ ...a })),\n ...(rec.memo !== undefined && rec.memo !== null\n ? { memo: asString(rec.memo, `${what}.memo`) }\n : {}),\n status,\n transferId: rec.transferId,\n createdAt,\n ...(expiresAt !== undefined ? { expiresAt } : {}),\n };\n}\n\n/**\n * `GET /v1/payment-requests?role=` → {@link PaymentRequestsPage} (§16). The\n * cursor family is role-bound: incoming pages carry the `?since=` seq counter,\n * outgoing pages an opaque keyset string (null once drained) — a page whose\n * cursor does not match its role is a protocol violation.\n */\nexport function parsePaymentRequestsPage(\n body: unknown,\n role: 'incoming' | 'outgoing'\n): PaymentRequestsPage {\n const rec = asRecord(body, 'payment-requests response');\n if (typeof rec.more !== 'boolean') throw protocolError('payment-requests response .more is not a boolean');\n const requests = asArray(rec.requests, 'payment-requests response .requests').map((raw, i) =>\n parsePaymentRequestRecord(raw, `requests[${i}]`)\n );\n const syncEpoch = parseCounter(rec.syncEpoch, 'payment-requests response .syncEpoch');\n if (role === 'incoming') {\n return {\n role,\n requests,\n more: rec.more,\n cursor: parseCounter(rec.cursor, 'payment-requests response .cursor'),\n syncEpoch,\n };\n }\n if (rec.cursor !== null && typeof rec.cursor !== 'string') {\n throw protocolError('payment-requests response .cursor is neither a keyset string nor null');\n }\n return { role, requests, more: rec.more, cursor: rec.cursor, syncEpoch };\n}\n\n// ── history (§10/§16) ─────────────────────────────────────────────────────────\n\nfunction parseHistoryRecord(raw: unknown, what: string): HistoryWireRecord {\n const rec = asRecord(raw, what);\n return {\n dedupKey: asString(rec.dedupKey, `${what}.dedupKey`),\n id: asString(rec.id, `${what}.id`),\n type: asString(rec.type, `${what}.type`),\n ts: asString(rec.ts, `${what}.ts`),\n assets: asArray(rec.assets, `${what}.assets`).map((a, i) => {\n const asset = asRecord(a, `${what}.assets[${i}]`);\n // Amounts stay decimal strings on this surface — display data (§10).\n parseAmount(asset.amount, `${what}.assets[${i}].amount`);\n return {\n coinId: asString(asset.coinId, `${what}.assets[${i}].coinId`),\n amount: asString(asset.amount, `${what}.assets[${i}].amount`),\n };\n }),\n ...(typeof rec.transferId === 'string' ? { transferId: rec.transferId } : {}),\n ...(typeof rec.tokenId === 'string' ? { tokenId: rec.tokenId } : {}),\n ...(typeof rec.counterpartyPubkey === 'string' ? { counterpartyPubkey: rec.counterpartyPubkey } : {}),\n ...(typeof rec.memo === 'string' ? { memo: rec.memo } : {}),\n ...(typeof rec.counterpartyNametag === 'string' ? { counterpartyNametag: rec.counterpartyNametag } : {}),\n };\n}\n\n/** `GET /v1/history` → {@link HistoryPage} (§16). */\nexport function parseHistoryPage(body: unknown): HistoryPage {\n const rec = asRecord(body, 'history response');\n if (typeof rec.more !== 'boolean') throw protocolError('history response .more is not a boolean');\n if (rec.cursor !== null && typeof rec.cursor !== 'string') {\n throw protocolError('history response .cursor is not a string or null');\n }\n return {\n records: asArray(rec.records, 'history response .records').map((raw, i) =>\n parseHistoryRecord(raw, `records[${i}]`)\n ),\n more: rec.more,\n cursor: rec.cursor,\n syncEpoch: parseCounter(rec.syncEpoch, 'history response .syncEpoch'),\n };\n}\n\n/** Auth responses (§4). */\nexport function parseAuthChallenge(body: unknown): { nonce: string; challenge: string } {\n const rec = asRecord(body, 'auth/challenge response');\n return {\n nonce: asString(rec.nonce, 'auth/challenge response .nonce'),\n challenge: asString(rec.challenge, 'auth/challenge response .challenge'),\n };\n}\n\nexport function parseAuthTokens(body: unknown): { jwt: string; refreshToken: string } {\n const rec = asRecord(body, 'auth token response');\n return {\n jwt: asString(rec.jwt, 'auth token response .jwt'),\n refreshToken: asString(rec.refreshToken, 'auth token response .refreshToken'),\n };\n}\n\n/** `POST /v1/ws-ticket` (§9). */\nexport function parseWsTicket(body: unknown): string {\n const rec = asRecord(body, 'ws-ticket response');\n return asString(rec.ticket, 'ws-ticket response .ticket');\n}\n\n/** WS wake frame (§9): `{ type:'wake', stream, syncEpoch }`. */\nexport function parseWakeFrame(raw: string): { stream: 'inventory' | 'mailbox' | 'payment_requests'; syncEpoch: bigint } | null {\n let body: unknown;\n try {\n body = JSON.parse(raw);\n } catch {\n return null;\n }\n if (typeof body !== 'object' || body === null) return null;\n const rec = body as Record<string, unknown>;\n if (rec.type !== 'wake') return null;\n const stream = rec.stream;\n if (stream !== 'inventory' && stream !== 'mailbox' && stream !== 'payment_requests') return null;\n try {\n return { stream, syncEpoch: parseCounter(rec.syncEpoch, 'wake .syncEpoch') };\n } catch {\n return null;\n }\n}\n","/**\n * Wake-socket reconnect supervisor (§9) — makes the single multiplexed wake\n * socket self-heal.\n *\n * The wake socket is a best-effort NUDGE; correctness is the pull. But a\n * SILENTLY dead socket starves every realtime consumer until a reload: the\n * server `terminate()`s on a missed heartbeat, hard-closes at access-token\n * expiry (code 4401), and proxies/idle/network/tab-suspend drop it — none of\n * which the bare `connectWakeSocket` observed once it nulled `onclose`/`onerror`\n * after open.\n *\n * This supervisor keeps `onclose`/`onerror` live and:\n * - reconnects on any drop with bounded exponential backoff + full jitter,\n * re-minting a fresh ticket each attempt (and refreshing the JWT on a 4401 /\n * auth-expiry close) — never giving up while the session is valid;\n * - runs a client-side liveness watchdog: any inbound signal (message, server\n * ping, or pong) is a sign of life; `2×` the server heartbeat of silence\n * means a half-open socket → force-close and reconnect;\n * - runs a full catch-up pull of ALL streams on every (re)connect (`onReconnect`)\n * — wakes missed during the dead window are gone (best-effort pub/sub), so\n * the client MUST full-resync to converge;\n * - distinguishes an intentional close (`destroy`/logout) from a drop so a\n * deliberate 4401 logout-close never spawns an infinite reconnect loop.\n *\n * Lives at the client layer because reconnecting re-mints a ws-ticket and may\n * refresh the JWT — both client-private. The socket OWNER (the MailboxProvider)\n * just supplies the catch-up/wake/status callbacks.\n */\nimport { WalletApiError } from './errors';\nimport { parseWakeFrame } from './codec';\nimport type {\n SuperviseWakeOptions,\n WakeSocketStatus,\n WebSocketLike,\n} from './types';\n\n/** App-defined WS close code: authentication gone — reconnect needs a fresh ticket + token (server `CLOSE_AUTH_GONE`, §9). */\nexport const CLOSE_AUTH_GONE = 4401;\n\nexport interface WakeSupervisorTiming {\n /** First reconnect delay; doubles each attempt up to {@link backoffCapMs}. */\n readonly backoffBaseMs: number;\n /** Backoff ceiling — the delay never exceeds this (before jitter). */\n readonly backoffCapMs: number;\n /**\n * Server heartbeat interval (§9 — 30 s). The liveness watchdog fires after\n * `2×` this of total silence (one whole missed ping/pong cycle + margin).\n */\n readonly heartbeatMs: number;\n}\n\nexport const DEFAULT_WAKE_TIMING: WakeSupervisorTiming = {\n backoffBaseMs: 500,\n backoffCapMs: 30_000,\n heartbeatMs: 30_000,\n};\n\n/** Injectable seams so tests drive time/randomness deterministically. */\nexport interface WakeSupervisorEnv {\n /** Re-mint a ticket and open ONE socket (no auto-reconnect). */\n readonly openSocket: () => Promise<WebSocketLike>;\n /** On a 4401/auth-gone close, drop the cached JWT so the next ticket mint re-auths. */\n readonly onAuthGone: () => void;\n readonly setTimeout: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>;\n readonly clearTimeout: (handle: ReturnType<typeof setTimeout>) => void;\n /** [0,1) — defaults to Math.random; injected for deterministic jitter in tests. */\n readonly random: () => number;\n}\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/**\n * Owns the lifecycle of ONE logical wake channel across reconnects. Construct,\n * call {@link start}, and {@link close} to tear down (idempotent).\n */\nexport class WakeSocketSupervisor {\n private status: WakeSocketStatus = 'connecting';\n private socket: WebSocketLike | null = null;\n private reconnectTimer: Timer | null = null;\n private watchdogTimer: Timer | null = null;\n private attempt = 0;\n private stopped = false;\n /** A reconnect cycle is already scheduled/in-flight — coalesce concurrent drop signals. */\n private reconnecting = false;\n\n constructor(\n private readonly opts: SuperviseWakeOptions,\n private readonly env: WakeSupervisorEnv,\n private readonly timing: WakeSupervisorTiming = DEFAULT_WAKE_TIMING\n ) {}\n\n get currentStatus(): WakeSocketStatus {\n return this.status;\n }\n\n /** Open the first socket; subsequent drops self-heal until {@link close}. */\n start(): void {\n void this.connect();\n }\n\n /** Idempotent teardown — no leaked timers or sockets, and no further reconnects. */\n close(): void {\n if (this.stopped) return;\n this.stopped = true;\n this.clearReconnect();\n this.clearWatchdog();\n this.detachAndClose(this.socket);\n this.socket = null;\n this.setStatus('closed');\n }\n\n // ── connect / drop ──────────────────────────────────────────────────────────\n\n private async connect(): Promise<void> {\n if (this.stopped) return;\n this.clearReconnect();\n try {\n const ws = await this.env.openSocket();\n if (this.stopped) {\n this.detachAndClose(ws);\n return;\n }\n this.adopt(ws);\n } catch (err) {\n if (this.stopped) return;\n // A failed mint/open is just another drop — back off and retry. A 401 in\n // the mint path already triggers the client's silent re-auth, so an\n // auth-expired ticket heals here too.\n this.onDrop(err instanceof WalletApiError && err.status === 401);\n }\n }\n\n /** Wire a freshly opened socket: keep onclose/onerror LIVE, arm the watchdog, run catch-up. */\n private adopt(ws: WebSocketLike): void {\n this.socket = ws;\n this.attempt = 0;\n this.reconnecting = false;\n ws.onmessage = (ev): void => this.onFrame(ev);\n ws.onerror = (): void => this.onDrop(false);\n ws.onclose = (ev): void => this.onClose(ev);\n // Ping/pong (when the transport surfaces them) are pure liveness signals.\n if ('onPing' in ws) ws.onPing = (): void => this.touch();\n if ('onPong' in ws) ws.onPong = (): void => this.touch();\n this.armWatchdog();\n this.setStatus('connected');\n // §9: wakes missed while dark are NOT replayed — full-resync every stream.\n this.opts.onReconnect?.();\n }\n\n private onFrame(ev: { data: unknown }): void {\n this.touch(); // any frame proves the socket is alive\n const frame = parseWakeFrame(typeof ev.data === 'string' ? ev.data : String(ev.data));\n if (frame) this.opts.onWake(frame);\n }\n\n private onClose(ev?: { code?: number }): void {\n this.onDrop(ev?.code === CLOSE_AUTH_GONE);\n }\n\n /** A drop from any cause: schedule a backed-off reconnect (unless intentionally stopped). */\n private onDrop(authGone: boolean): void {\n if (this.stopped) return;\n if (authGone) this.env.onAuthGone(); // force a token refresh on the next mint\n if (this.reconnecting) return; // a reconnect is already queued — don't pile up\n this.reconnecting = true;\n this.clearWatchdog();\n this.detachAndClose(this.socket);\n this.socket = null;\n this.setStatus('reconnecting');\n this.scheduleReconnect();\n }\n\n private scheduleReconnect(): void {\n const delay = this.backoffDelay(this.attempt);\n this.attempt += 1;\n this.reconnectTimer = this.env.setTimeout(() => {\n this.reconnectTimer = null;\n void this.connect();\n }, delay);\n }\n\n /** Exponential `base·2^n` capped at `cap`, then full jitter in `[0, capped]` (thundering-herd guard). */\n private backoffDelay(attempt: number): number {\n const capped = Math.min(this.timing.backoffCapMs, this.timing.backoffBaseMs * 2 ** attempt);\n return Math.floor(this.env.random() * capped);\n }\n\n // ── liveness watchdog ────────────────────────────────────────────────────────\n\n /** Mark the socket alive — re-arm the silence watchdog. */\n private touch(): void {\n if (this.stopped || !this.socket) return;\n this.armWatchdog();\n }\n\n private armWatchdog(): void {\n this.clearWatchdog();\n this.watchdogTimer = this.env.setTimeout(() => {\n this.watchdogTimer = null;\n // Silence for a whole heartbeat cycle ⇒ half-open. Force a reconnect.\n this.onDrop(false);\n }, this.timing.heartbeatMs * 2);\n }\n\n private clearWatchdog(): void {\n if (this.watchdogTimer !== null) {\n this.env.clearTimeout(this.watchdogTimer);\n this.watchdogTimer = null;\n }\n }\n\n private clearReconnect(): void {\n if (this.reconnectTimer !== null) {\n this.env.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n }\n\n /** Detach our handlers (so a late close from THIS socket can't re-trigger) then close it. */\n private detachAndClose(ws: WebSocketLike | null): void {\n if (!ws) return;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n if ('onPing' in ws) ws.onPing = null;\n if ('onPong' in ws) ws.onPong = null;\n try {\n ws.close();\n } catch {\n // already closing/closed — nothing to do\n }\n }\n\n private setStatus(status: WakeSocketStatus): void {\n if (this.status === status) return;\n this.status = status;\n this.opts.onStatus?.(status);\n }\n}\n","/**\n * wallet-api/client.ts — `WalletApiClient` (sdk-changes S1).\n *\n * A small typed client for the wallet-api backend: challenge→sign→JWT with a\n * rotating refresh token, typed REST for the §16 endpoints, and the WS wake\n * channel (ticket flow — §9). Injected into providers (DI; no singletons).\n *\n * Cross-cutting rules (S1):\n * - **Challenge template verification** — the spend key never signs text that\n * fails `verifyChallengeTemplate` (prefix + own pubkey + plausible\n * timestamps). See ./challenge.ts.\n * - **Credential hygiene** — the refresh token lives only in the injected\n * {@link KeyValueStore} (never a URL, never logged). A rotation-reuse\n * revocation or refresh expiry falls back to a fresh challenge→sign cycle —\n * silent, since the wallet key is available at unlock. Non-loopback base\n * URLs MUST be `https:` (ARCHITECTURE §4 transport rule), enforced at\n * construction.\n * - **Amounts are decimal strings end-to-end**, parsed with `BigInt` (§11) —\n * see ./codec.ts.\n *\n * The client also keeps the NORMATIVE LOCAL COPY of open intents (E.3): the\n * server is the primary, but intents are the one server table not\n * re-derivable from blobs — after a server restore (`syncEpoch` change,\n * ARCHITECTURE §5.4) the client re-PUTs its locally-known open intents\n * (idempotent) before anything resumes. `putIntent` persists locally before\n * the server PUT; the local copy survives a failed PUT as the restore\n * backstop.\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { signMessage } from '../core/crypto';\nimport { WalletApiError } from './errors';\nimport { verifyChallengeTemplate } from './challenge';\nimport {\n WakeSocketSupervisor,\n DEFAULT_WAKE_TIMING,\n type WakeSupervisorTiming,\n} from './wake-supervisor';\nimport {\n parseApplyResult,\n parseAuthChallenge,\n parseAuthTokens,\n parseBalances,\n parseBlobUrls,\n parseClaimResult,\n parseDepositResult,\n parseHistoryPage,\n parseIntents,\n parseInventoryPage,\n parseMailboxPage,\n parsePaymentRequestRecord,\n parsePaymentRequestsPage,\n parseRejectResult,\n parseUploadUrls,\n parseWakeFrame,\n parseWsTicket,\n} from './codec';\nimport type {\n ApplyDeltaRequest,\n BlobUrlEntry,\n CoinBalance,\n CreatePaymentRequestInput,\n FetchLike,\n FetchResponseLike,\n HistoryPage,\n HistoryWireRecord,\n IntentRecord,\n InventoryPage,\n KeyValueStore,\n ListPaymentRequestsParams,\n MailboxClaimResult,\n MailboxDepositRequest,\n MailboxPage,\n PaymentRequestRecord,\n PaymentRequestsPage,\n RespondPaymentRequestInput,\n SupervisedWakeSocketHandle,\n SuperviseWakeOptions,\n UploadUrlEntry,\n UploadUrlRequest,\n WakeCallback,\n WakeSocketHandle,\n WalletApiClientConfig,\n WalletApiIdentity,\n WebSocketFactoryLike,\n WebSocketLike,\n} from './types';\n\ninterface LocalIntent {\n payload: string;\n status: 'open' | 'completed' | 'aborted';\n createdAt: number;\n /**\n * #516: set when the abort decision could NOT land on the server (dead\n * backend at send-failure cleanup). {@link WalletApiClient.resyncOpenIntents}\n * replays it (PUT + abort) so the server row converges to aborted instead of\n * resume re-executing a send the user watched fail.\n */\n abortPending?: boolean;\n}\n\nfunction isLoopbackHost(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname.endsWith('.localhost') ||\n /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(hostname) ||\n hostname === '::1' ||\n hostname === '[::1]'\n );\n}\n\n/** Enforce the §4 transport rule: non-loopback MUST be https. */\nfunction assertSecureBaseUrl(baseUrl: string): URL {\n let url: URL;\n try {\n url = new URL(baseUrl);\n } catch {\n throw new WalletApiError(`Invalid wallet-api base URL: ${baseUrl}`, 'CONFIG');\n }\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHost(url.hostname))) {\n throw new WalletApiError(\n 'wallet-api base URL must be https (plain http is allowed only on loopback — ARCHITECTURE §4)',\n 'CONFIG'\n );\n }\n return url;\n}\n\n/** Platform-neutral bytes→base64 (browser btoa + Node ≥16 global btoa). */\nfunction bytesToBase64(bytes: Uint8Array): string {\n let bin = '';\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin);\n}\n\nfunction defaultWebSocketFactory(url: string): import('./types').WebSocketLike {\n const Ctor = (globalThis as { WebSocket?: new (url: string) => import('./types').WebSocketLike }).WebSocket;\n if (!Ctor) {\n throw new WalletApiError(\n 'No global WebSocket available — inject webSocketFactory (e.g. the \"ws\" package on Node < 22)',\n 'CONFIG'\n );\n }\n return new Ctor(url);\n}\n\nexport class WalletApiClient {\n /** Network name (also the blob-key prefix `<network>/t/<sha256>` — §5.2). */\n readonly network: string;\n\n private readonly baseUrl: string;\n private readonly deviceId: string;\n private readonly storage: KeyValueStore;\n private readonly fetchFn: FetchLike;\n private readonly wsFactory: WebSocketFactoryLike;\n private readonly now: () => number;\n\n private identity: WalletApiIdentity | null = null;\n private jwt: string | null = null;\n /** Serializes concurrent re-auth attempts. */\n private authInFlight: Promise<void> | null = null;\n /**\n * #583: monotonic auth-session counter. Bumped by every {@link setIdentity}\n * and {@link logout}. A sign-in/refresh attempt captures it at its START and\n * bails before any shared-state mutation (`this.jwt`, the refresh token) if it\n * no longer matches — i.e. the identity moved on while the attempt was async,\n * so its result is stale and would contaminate the new owner. See\n * {@link isStale}.\n */\n private authGeneration = 0;\n\n /** The construction config, retained so {@link clone} can mint a sibling. */\n private readonly config: WalletApiClientConfig;\n\n constructor(config: WalletApiClientConfig) {\n const url = assertSecureBaseUrl(config.baseUrl);\n this.baseUrl = url.toString().replace(/\\/$/, '');\n if (!config.network) throw new WalletApiError('network is required', 'CONFIG');\n this.network = config.network;\n this.deviceId = config.deviceId;\n this.storage = config.storage;\n if (!config.fetchFn && !(globalThis as { fetch?: FetchLike }).fetch) {\n throw new WalletApiError('No fetch available — inject fetchFn', 'CONFIG');\n }\n // Resolve the global lazily THROUGH globalThis so the implementation keeps\n // its original receiver (browser fetch throws \"Illegal invocation\" when\n // called detached).\n this.fetchFn =\n config.fetchFn ?? ((u, init) => (globalThis as unknown as { fetch: FetchLike }).fetch(u, init));\n this.wsFactory = config.webSocketFactory ?? defaultWebSocketFactory;\n this.now = config.now ?? (() => Date.now());\n this.config = config;\n }\n\n /**\n * #583: mint a FRESH, identity-less sibling client from the SAME construction\n * config (baseUrl, network, deviceId, storage, fetch/ws factories, clock).\n * Per-address client isolation builds one client per HD address from this, so\n * each address's providers authenticate as their OWN owner with their OWN JWT\n * — an orphaned previous-address poll pump can never drive a client that has\n * been re-authed to a DIFFERENT owner. The shared `storage` is intentional:\n * its keys are namespaced per (network, chainPubkey, deviceId), so per-owner\n * refresh tokens / cursors stay separate (no cross-owner collision). The clone\n * starts with no identity and no JWT — the caller binds it via setIdentity.\n */\n clone(): WalletApiClient {\n return new WalletApiClient(this.config);\n }\n\n /** Bind the wallet identity this client authenticates as. Resets the session. */\n setIdentity(identity: WalletApiIdentity): void {\n this.identity = identity;\n this.jwt = null;\n // #583: invalidate any in-flight sign-in for the PREVIOUS identity. Nulling\n // `authInFlight` only drops our reference — the orphaned challenge→sign /\n // refresh chain keeps running and could STILL resolve later, at which point\n // it would (a) cache `this.jwt` for the wrong owner and (b) write/clear the\n // refresh token under `refreshTokenKey()`, which is now derived from the NEW\n // identity — cross-owner contamination. Bumping `authGeneration` makes those\n // late mutations self-cancel: every attempt captured the generation at its\n // start and `isStale()`-guards each shared-state write, so a stale chain\n // discards its result instead of clobbering the new owner's session.\n this.authGeneration += 1;\n this.authInFlight = null;\n }\n\n // ── storage keys (scoped per network + pubkey + device) ────────────────────\n\n private requireIdentity(): WalletApiIdentity {\n if (!this.identity) throw new WalletApiError('No identity set — call setIdentity() first', 'CONFIG');\n return this.identity;\n }\n\n private scopedKey(kind: string): string {\n const { chainPubkey } = this.requireIdentity();\n return `wallet-api:${kind}:${this.network}:${chainPubkey}`;\n }\n\n private refreshTokenKey(): string {\n return `${this.scopedKey('refresh')}:${this.deviceId}`;\n }\n\n /**\n * #583: true once the identity has moved on since `gen` was captured (a\n * {@link setIdentity}/{@link logout} bumped {@link authGeneration}). A sign-in\n * attempt checks this before every mutation of `this.jwt` or the refresh token\n * and bails out when stale — its tokens belong to a now-discarded owner.\n */\n private isStale(gen: number): boolean {\n return this.authGeneration !== gen;\n }\n\n // ── auth (ARCHITECTURE §4) ──────────────────────────────────────────────────\n\n /**\n * Establish a session: try the stored refresh token first (rotating), fall\n * back to a fresh challenge→sign→verify cycle. Safe to call repeatedly.\n */\n async signIn(): Promise<void> {\n if (this.authInFlight) return this.authInFlight;\n // #583: bind this attempt to the CURRENT auth generation. A later\n // setIdentity()/logout() bumps the generation; the attempt then self-cancels\n // before mutating shared state (see `signInInner`/`tryRefresh`/`challengeSignIn`).\n const gen = this.authGeneration;\n const inFlight = this.signInInner(gen).finally(() => {\n // #583: only clear the slot if it still holds THIS promise. setIdentity()\n // may null `authInFlight` (abandoning a stale sign-in) and a fresh signIn()\n // may have stored a NEW promise; an unconditional clear here would clobber\n // that newer in-flight sign-in and break the de-dup guarantee.\n if (this.authInFlight === inFlight) this.authInFlight = null;\n });\n this.authInFlight = inFlight;\n return inFlight;\n }\n\n private async signInInner(gen: number): Promise<void> {\n if (await this.tryRefresh(gen)) return;\n // #583: `tryRefresh` returns false for TWO reasons — a genuine refresh miss\n // (no/expired token) OR the identity moved on mid-refresh (`isStale`). In the\n // stale case we must NOT fall through to a challenge→verify cycle: it would\n // run under the NEW owner, hit the network, possibly throw, and be discarded\n // by `challengeSignIn`'s own end-guard anyway. Bail cleanly instead.\n if (this.isStale(gen)) return;\n await this.challengeSignIn(gen);\n }\n\n /**\n * `POST /v1/auth/refresh` with the stored token; rotates on success. Any\n * 4xx (expired, revoked, rotation-reuse revocation) clears the stored token\n * and reports `false` — the caller falls back to a challenge cycle.\n */\n private async tryRefresh(gen: number): Promise<boolean> {\n // #583: capture the refresh-token key NOW. The whole attempt operates on\n // THIS owner's key; a mid-flight identity switch repoints `refreshTokenKey()`\n // at the new owner, so we must never read or write under the new key here.\n const key = this.refreshTokenKey();\n const stored = await this.storage.get(key);\n if (!stored) return false;\n const res = await this.rawFetch('POST', '/v1/auth/refresh', { refreshToken: stored });\n // The identity may have moved on while the request was in flight — discard\n // the result rather than caching the previous owner's JWT / refresh token.\n if (this.isStale(gen)) return false;\n if (res.status === 200) {\n const tokens = parseAuthTokens(await this.readJson(res, 'auth/refresh'));\n this.jwt = tokens.jwt;\n await this.storage.set(key, tokens.refreshToken);\n return true;\n }\n // Stale/revoked/reused token — discard it; a fresh challenge cycle follows.\n await this.storage.remove(key);\n return false;\n }\n\n /** The challenge→verify cycle (§4 steps 1–3) with template verification (S1). */\n private async challengeSignIn(gen: number): Promise<void> {\n const identity = this.requireIdentity();\n // #583: pin the refresh-token key to THIS owner up front (it is derived from\n // the identity); a mid-flight switch must not write under the new owner's key.\n const key = this.refreshTokenKey();\n const challengeRes = await this.rawFetch('POST', '/v1/auth/challenge', {\n pubkey: identity.chainPubkey,\n });\n if (challengeRes.status !== 200) throw await this.toError(challengeRes, 'auth/challenge');\n const { nonce, challenge } = parseAuthChallenge(await this.readJson(challengeRes, 'auth/challenge'));\n\n // The spend key never signs unverified server-chosen text (S1).\n verifyChallengeTemplate(challenge, {\n pubkey: identity.chainPubkey,\n nonce,\n network: this.network,\n nowMs: this.now(),\n });\n\n const signature = signMessage(identity.privateKey, challenge);\n const verifyRes = await this.rawFetch('POST', '/v1/auth/verify', {\n nonce,\n signature,\n deviceId: this.deviceId,\n });\n if (verifyRes.status !== 200) throw await this.toError(verifyRes, 'auth/verify');\n const tokens = parseAuthTokens(await this.readJson(verifyRes, 'auth/verify'));\n // The identity may have switched while challenge→verify was in flight —\n // discard this owner's freshly-minted session instead of caching the JWT /\n // persisting the refresh token under the new owner's storage key.\n if (this.isStale(gen)) return;\n this.jwt = tokens.jwt;\n await this.storage.set(key, tokens.refreshToken);\n }\n\n /** Revoke the session server-side and drop all local credentials. */\n async logout(): Promise<void> {\n // #583: invalidate any in-flight sign-in so it cannot re-cache a JWT or\n // re-persist the refresh token after we have just dropped them.\n this.authGeneration += 1;\n this.authInFlight = null;\n if (this.jwt) {\n try {\n await this.rawFetch('POST', '/v1/auth/logout', {}, this.jwt);\n } finally {\n this.jwt = null;\n }\n }\n await this.storage.remove(this.refreshTokenKey());\n }\n\n // ── request core ────────────────────────────────────────────────────────────\n\n private async rawFetch(\n method: string,\n path: string,\n body?: unknown,\n jwt?: string\n ): Promise<FetchResponseLike> {\n const headers: Record<string, string> = {};\n if (body !== undefined) headers['content-type'] = 'application/json';\n if (jwt) headers['authorization'] = `Bearer ${jwt}`;\n try {\n return await this.fetchFn(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n } catch (err) {\n throw new WalletApiError(`wallet-api request failed: ${method} ${path}`, 'NETWORK', undefined, err);\n }\n }\n\n private async readJson(res: FetchResponseLike, what: string): Promise<unknown> {\n const text = await res.text();\n if (text === '') return null;\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new WalletApiError(`${what}: response is not JSON`, 'PROTOCOL', res.status, err);\n }\n }\n\n private async toError(res: FetchResponseLike, what: string): Promise<WalletApiError> {\n let message = `${what} failed with status ${res.status}`;\n try {\n const body = (await this.readJson(res, what)) as { error?: { code?: string; message?: string } } | null;\n if (body?.error?.message) message = `${what}: ${body.error.code ?? ''} ${body.error.message}`.trim();\n } catch {\n // keep the generic message\n }\n return WalletApiError.fromStatus(res.status, message);\n }\n\n /**\n * Authenticated JSON request. A 401 triggers one silent re-auth\n * (refresh → challenge fallback) and one retry.\n */\n private async requestJson(method: string, path: string, body?: unknown): Promise<unknown> {\n if (!this.jwt) await this.signIn();\n let res = await this.rawFetch(method, path, body, this.jwt!);\n if (res.status === 401) {\n this.jwt = null;\n await this.signIn();\n res = await this.rawFetch(method, path, body, this.jwt!);\n }\n if (res.status === 204) return null;\n if (!res.ok) throw await this.toError(res, `${method} ${path}`);\n return this.readJson(res, `${method} ${path}`);\n }\n\n // ── inventory / blobs (§16) ─────────────────────────────────────────────────\n\n /** `GET /v1/inventory?since=` — one page; the caller loops while `more`. */\n async listInventory(since?: bigint): Promise<InventoryPage> {\n const query = since !== undefined ? `?since=${since.toString()}` : '';\n const page = parseInventoryPage(await this.requestJson('GET', `/v1/inventory${query}`));\n await this.noteSyncEpoch(page.syncEpoch);\n return page;\n }\n\n /** `GET /v1/balances` — active rows only. */\n async getBalances(): Promise<CoinBalance[]> {\n return parseBalances(await this.requestJson('GET', '/v1/balances'));\n }\n\n /** `POST /v1/tokens/blob-urls` — owner's active *or tombstoned* rows (§5.3 recovery). */\n async getBlobUrls(tokenIds: string[]): Promise<BlobUrlEntry[]> {\n return parseBlobUrls(await this.requestJson('POST', '/v1/tokens/blob-urls', { tokenIds }));\n }\n\n /** `POST /v1/tokens/upload-urls` — checksum/length-bound presigned PUTs (§5.2). */\n async getUploadUrls(blobs: UploadUrlRequest[]): Promise<UploadUrlEntry[]> {\n return parseUploadUrls(await this.requestJson('POST', '/v1/tokens/upload-urls', { blobs }));\n }\n\n /**\n * `POST /v1/inventory/apply` (§5.3). Also marks the local intent copy\n * completed — the server completes the intent in the same transaction (§16).\n */\n async applyInventoryDelta(req: ApplyDeltaRequest): Promise<bigint> {\n const cursor = parseApplyResult(\n await this.requestJson('POST', '/v1/inventory/apply', {\n transferId: req.transferId,\n spent: req.spent,\n added: req.added,\n ...(req.externalDelivery !== undefined ? { externalDelivery: req.externalDelivery } : {}),\n })\n );\n await this.setLocalIntentStatus(req.transferId, 'completed');\n return cursor;\n }\n\n /** Download blob bytes from a signed GET URL (the URL itself is the credential). */\n async fetchBlob(getUrl: string): Promise<Uint8Array> {\n let res: FetchResponseLike;\n try {\n res = await this.fetchFn(getUrl, { method: 'GET' });\n } catch (err) {\n throw new WalletApiError('blob download failed', 'NETWORK', undefined, err);\n }\n if (!res.ok) throw WalletApiError.fromStatus(res.status, `blob download failed with status ${res.status}`);\n return new Uint8Array(await res.arrayBuffer());\n }\n\n /**\n * Upload blob bytes to a signed PUT URL. A `412 Precondition Failed` means\n * the identical blob already exists (content addressing, `If-None-Match: *`\n * — §5.2) and is treated as success.\n *\n * The §5.2 presign binds `x-amz-checksum-sha256` and `if-none-match` (plus\n * `content-length`) as SIGNED HEADERS — a real S3 endpoint rejects the\n * SigV4 signature unless the uploader sends them verbatim. (Caught by the\n * phase-2 harness on first contact with real MinIO — the in-process fake\n * had only validated the body, not the signed headers.)\n */\n async uploadBlob(putUrl: string, bytes: Uint8Array): Promise<void> {\n let res: FetchResponseLike;\n try {\n res = await this.fetchFn(putUrl, {\n method: 'PUT',\n headers: {\n 'content-type': 'application/octet-stream',\n 'x-amz-checksum-sha256': bytesToBase64(sha256(bytes)),\n 'if-none-match': '*',\n },\n body: bytes,\n });\n } catch (err) {\n throw new WalletApiError('blob upload failed', 'NETWORK', undefined, err);\n }\n if (res.ok || res.status === 412) return;\n throw WalletApiError.fromStatus(res.status, `blob upload failed with status ${res.status}`);\n }\n\n // ── mailbox (§6/§16) ────────────────────────────────────────────────────────\n\n /**\n * `POST /v1/mailbox` — deposit an already-uploaded finished blob to the\n * recipient's mailbox. Idempotent by content-derived `entry_id` (§6): an\n * existing entry in any status returns `200` with its id, provided the\n * request's recipient and key match the stored entry (a mismatch is `409`).\n */\n async depositMailbox(req: MailboxDepositRequest): Promise<string> {\n return parseDepositResult(\n await this.requestJson('POST', '/v1/mailbox', {\n recipientPubkey: req.recipientPubkey,\n key: req.key,\n transferId: req.transferId,\n stateHash: req.stateHash,\n tokenId: req.tokenId,\n ...(req.memo !== undefined ? { memo: req.memo } : {}),\n })\n );\n }\n\n /**\n * `GET /v1/mailbox?since=<seq>` — entries of EVERY status are listable for\n * any client-chosen `since`; a claimed entry carries a working `getUrl`\n * while its blob is within retention, `blobCollected: true` afterwards (§6).\n */\n async listMailbox(since?: bigint): Promise<MailboxPage> {\n const query = since !== undefined ? `?since=${since.toString()}` : '';\n const page = parseMailboxPage(await this.requestJson('GET', `/v1/mailbox${query}`));\n await this.noteSyncEpoch(page.syncEpoch);\n return page;\n }\n\n /**\n * `POST /v1/mailbox/claim` — addressee-only, idempotent ownership handoff\n * (§6). `intoInventory:false` is the delivery-only claim: the entry resolves\n * and the pointer advances with ZERO inventory writes.\n */\n async claimMailbox(entryIds: string[], intoInventory: boolean): Promise<MailboxClaimResult> {\n return parseClaimResult(\n await this.requestJson('POST', '/v1/mailbox/claim', { entryIds, intoInventory })\n );\n }\n\n /**\n * `POST /v1/mailbox/reject` — addressee-only; terminal for DISCOVERY only:\n * the entry counts toward read-pointer contiguity but remains claimable and\n * its blob is retained (§6 — reject is never a destruction path).\n */\n async rejectMailbox(entryIds: string[]): Promise<string[]> {\n return parseRejectResult(await this.requestJson('POST', '/v1/mailbox/reject', { entryIds }));\n }\n\n // ── history (§10/§16) ───────────────────────────────────────────────────────\n\n /**\n * `POST /v1/history` — client-asserted records, deduped by `dedupKey` (the\n * server never writes history rows — §10). `memo`/`counterpartyNametag`\n * MUST already be S6 envelopes.\n */\n async postHistoryRecords(records: HistoryWireRecord[]): Promise<void> {\n await this.requestJson('POST', '/v1/history', { records });\n }\n\n /** `GET /v1/history?before=&limit=` — newest-first keyset pages (§10). */\n async listHistory(options: { before?: string; limit?: number } = {}): Promise<HistoryPage> {\n const params = new URLSearchParams();\n if (options.before !== undefined) params.set('before', options.before);\n if (options.limit !== undefined) params.set('limit', String(options.limit));\n const qs = params.toString();\n return parseHistoryPage(await this.requestJson('GET', `/v1/history${qs ? `?${qs}` : ''}`));\n }\n\n // ── payment requests (§10/§16) ──────────────────────────────────────────────\n\n /**\n * `POST /v1/payment-requests` — create a request addressed to a payer (the\n * payer's account is auto-provisioned even if they never authenticated —\n * §4/§9; the per-payer open cap → 429, §5.5). `memo` MUST already be an S6\n * `enc1.` envelope (§8.3) — only the requester's wallet key decrypts it.\n */\n async createPaymentRequest(input: CreatePaymentRequestInput): Promise<PaymentRequestRecord> {\n return parsePaymentRequestRecord(\n await this.requestJson('POST', '/v1/payment-requests', {\n toPubkey: input.toPubkey,\n // Amounts are decimal strings in every JSON body (§11).\n assets: input.assets.map((a) => ({ coinId: a.coinId, amount: a.amount.toString() })),\n ...(input.memo !== undefined ? { memo: input.memo } : {}),\n ...(input.expiresAt !== undefined ? { expiresAt: new Date(input.expiresAt).toISOString() } : {}),\n }),\n 'payment-request create response'\n );\n }\n\n /**\n * `GET /v1/payment-requests?role=…` (§16): `'incoming'` is the payer's\n * gap-free `?since=<seq>` stream (cursor = bigint, the standard §16 since\n * contract); `'outgoing'` is the requester's newest-first\n * `?before=<opaque keyset>` backfill (cursor = string | null). The two\n * cursor families never mix — the server 422s a mismatched parameter, and\n * the parameter types make it unrepresentable here.\n */\n async listPaymentRequests<R extends 'incoming' | 'outgoing'>(\n params: Extract<ListPaymentRequestsParams, { role: R }>\n ): Promise<Extract<PaymentRequestsPage, { role: R }>> {\n // Widened to the plain union — generic Extract<> members don't narrow.\n const p: ListPaymentRequestsParams = params;\n const query = new URLSearchParams();\n query.set('role', p.role);\n if (p.status !== undefined) query.set('status', p.status);\n if (p.role === 'incoming') {\n if (p.since !== undefined) query.set('since', p.since.toString());\n } else if (p.before !== undefined) {\n query.set('before', p.before);\n }\n const page = parsePaymentRequestsPage(\n await this.requestJson('GET', `/v1/payment-requests?${query.toString()}`),\n p.role\n );\n await this.noteSyncEpoch(page.syncEpoch);\n // The codec already discriminated the page by role; Extract<> re-states\n // the role-bound cursor family to the caller.\n return page as Extract<PaymentRequestsPage, { role: R }>;\n }\n\n /**\n * `POST /v1/payment-requests/{id}/respond` — addressee-only (§10, non-\n * addressee → 403); only an `open` request may be responded to (else 409).\n * `paid` REQUIRES and links the fulfilling send's transferId, `declined`\n * carries none — the pairing is enforced by {@link RespondPaymentRequestInput}.\n */\n async respondPaymentRequest(id: string, response: RespondPaymentRequestInput): Promise<PaymentRequestRecord> {\n return parsePaymentRequestRecord(\n await this.requestJson('POST', `/v1/payment-requests/${id}/respond`, response),\n 'payment-request respond response'\n );\n }\n\n // ── intents (E.3) ───────────────────────────────────────────────────────────\n\n private intentsKey(): string {\n return this.scopedKey('intents');\n }\n\n private async readLocalIntents(): Promise<Record<string, LocalIntent>> {\n const raw = await this.storage.get(this.intentsKey());\n if (!raw) return {};\n try {\n return JSON.parse(raw) as Record<string, LocalIntent>;\n } catch {\n return {};\n }\n }\n\n private async writeLocalIntents(intents: Record<string, LocalIntent>): Promise<void> {\n await this.storage.set(this.intentsKey(), JSON.stringify(intents));\n }\n\n private async setLocalIntentStatus(\n transferId: string,\n status: LocalIntent['status'],\n opts: { abortPending?: boolean } = {}\n ): Promise<void> {\n const intents = await this.readLocalIntents();\n const intent = intents[transferId];\n if (!intent) return;\n if (intent.status === 'completed') return; // completed never reverts (§16)\n const abortPending = opts.abortPending === true;\n if (intent.status === status && (intent.abortPending === true) === abortPending) return;\n intent.status = status;\n if (abortPending) intent.abortPending = true;\n else delete intent.abortPending;\n await this.writeLocalIntents(intents);\n }\n\n /**\n * Persist a (client-encrypted — S6) intent payload: LOCAL copy first, then\n * `PUT /v1/intents/{transferId}` and await the server ack (E.3 — the engine\n * MUST NOT be called before this resolves). A failed server PUT throws, but\n * the local copy stays as the restore backstop and is re-PUT by\n * {@link resyncOpenIntents}.\n */\n async putIntent(transferId: string, payloadEnvelope: string): Promise<void> {\n const intents = await this.readLocalIntents();\n if (!intents[transferId]) {\n intents[transferId] = { payload: payloadEnvelope, status: 'open', createdAt: this.now() };\n await this.writeLocalIntents(intents);\n }\n await this.requestJson('PUT', `/v1/intents/${transferId}`, { payload: payloadEnvelope });\n }\n\n /** `GET /v1/intents?status=` — server-side intent list. */\n async listIntents(status: 'open' | 'aborted'): Promise<IntentRecord[]> {\n return parseIntents(await this.requestJson('GET', `/v1/intents?status=${status}`));\n }\n\n /**\n * `POST /v1/intents/{id}/abort` — soft, recoverable (§16).\n *\n * #516: the LOCAL copy flips to 'aborted' even when the server abort cannot\n * land (dead backend) — leaving it 'open' would make {@link resyncOpenIntents}\n * re-PUT it and the next sign-in's `resumeOpenIntents` RE-EXECUTE a send the\n * user watched fail (and possibly retried manually): a double-pay hazard.\n * An unlanded abort is marked pending and replayed by\n * {@link resyncOpenIntents} (PUT + abort) so the server converges too.\n */\n async abortIntent(transferId: string): Promise<void> {\n try {\n await this.requestJson('POST', `/v1/intents/${transferId}/abort`);\n } catch (err) {\n await this.setLocalIntentStatus(transferId, 'aborted', { abortPending: true });\n throw err;\n }\n await this.setLocalIntentStatus(transferId, 'aborted');\n }\n\n /** `POST /v1/intents/{id}/complete` — the uniform client-side close (E.3). */\n async completeIntent(transferId: string): Promise<void> {\n await this.requestJson('POST', `/v1/intents/${transferId}/complete`);\n await this.setLocalIntentStatus(transferId, 'completed');\n }\n\n /** The locally-known open intents (the E.3 restore backstop). */\n async listLocalOpenIntents(): Promise<IntentRecord[]> {\n const intents = await this.readLocalIntents();\n return Object.entries(intents)\n .filter(([, i]) => i.status === 'open')\n .map(([transferId, i]) => ({ transferId, payload: i.payload, status: 'open' as const, createdAt: i.createdAt }));\n }\n\n /**\n * Re-PUT every locally-known open intent (idempotent — the server PUT is\n * write-once while open/completed). Called after a `syncEpoch` change\n * (server restore — §5.4): intents are the one server table not\n * re-derivable from blobs.\n *\n * #516: also replays locally-aborted intents whose abort never landed on\n * the server (`abortPending`) — PUT (no-op while open/completed; (re)creates\n * the row after a restore or a failed original PUT) then abort, so the\n * server row lands as 'aborted' instead of an 'open' intent that resume\n * would re-execute. Completed-wins is preserved server-side (§16).\n */\n async resyncOpenIntents(): Promise<void> {\n const intents = await this.readLocalIntents();\n for (const [transferId, intent] of Object.entries(intents)) {\n if (intent.status === 'open') {\n await this.requestJson('PUT', `/v1/intents/${transferId}`, { payload: intent.payload });\n } else if (intent.status === 'aborted' && intent.abortPending === true) {\n await this.requestJson('PUT', `/v1/intents/${transferId}`, { payload: intent.payload });\n await this.requestJson('POST', `/v1/intents/${transferId}/abort`);\n await this.setLocalIntentStatus(transferId, 'aborted'); // clears abortPending\n }\n }\n }\n\n // ── syncEpoch (§5.4/§9) ─────────────────────────────────────────────────────\n\n private syncEpochKey(): string {\n return this.scopedKey('syncEpoch');\n }\n\n /**\n * Track the server `syncEpoch` carried by cursor-bearing responses and\n * wakes. On a change (server restore), re-PUT locally-known open intents\n * before anything resumes (E.3). Storage-provider cursor invalidation is\n * the provider's own duty (S2) — it observes the same epoch values.\n */\n private async noteSyncEpoch(epoch: bigint): Promise<void> {\n const stored = await this.storage.get(this.syncEpochKey());\n if (stored === epoch.toString()) return;\n await this.storage.set(this.syncEpochKey(), epoch.toString());\n if (stored !== null) {\n await this.resyncOpenIntents();\n }\n }\n\n // ── realtime (§9) ───────────────────────────────────────────────────────────\n\n /**\n * Open the wake channel: `POST /v1/ws-ticket` (JWT-authed, single-use,\n * short TTL) then `GET /v1/ws?ticket=…` — the JWT never appears in a URL.\n * Wakes are nudges only; correctness comes from the `?since=` cursors.\n */\n async connectWakeSocket(onWake: WakeCallback): Promise<WakeSocketHandle> {\n const ws = await this.openWakeSocket();\n ws.onerror = null;\n ws.onclose = null;\n ws.onmessage = (ev) => {\n const frame = parseWakeFrame(typeof ev.data === 'string' ? ev.data : String(ev.data));\n if (!frame) return;\n void this.noteSyncEpoch(frame.syncEpoch);\n onWake(frame);\n };\n return { close: () => ws.close() };\n }\n\n /**\n * Mint a single-use ticket (a 401 silently re-auths via {@link requestJson}),\n * upgrade to a wake socket and resolve once it opens. ONE socket, no\n * auto-reconnect — the building block reused by {@link connectWakeSocket} and\n * the {@link superviseWakeSocket} supervisor.\n */\n private async openWakeSocket(): Promise<WebSocketLike> {\n const ticket = parseWsTicket(await this.requestJson('POST', '/v1/ws-ticket'));\n const wsBase = this.baseUrl.replace(/^http/, 'ws');\n const ws = this.wsFactory(`${wsBase}/v1/ws?ticket=${encodeURIComponent(ticket)}`);\n await new Promise<void>((resolve, reject) => {\n ws.onopen = () => resolve();\n ws.onerror = (err) => reject(new WalletApiError('wake socket failed to connect', 'NETWORK', undefined, err));\n ws.onclose = () => reject(new WalletApiError('wake socket closed before connecting', 'NETWORK'));\n });\n return ws;\n }\n\n /**\n * Open a SELF-HEALING wake channel (§9): the supervisor keeps the socket\n * alive across drops — bounded backoff + jitter reconnects (fresh ticket each\n * attempt; a 4401/auth-gone close also refreshes the token), a client-side\n * liveness watchdog that force-reconnects a half-open socket, and a full\n * catch-up pull of every stream on each (re)connect (`onReconnect`) so a dead\n * window converges WITHOUT waiting for the poll. `onStatus` surfaces true\n * socket liveness, decoupled from sign-in state. `close()` tears it down with\n * no further reconnects (a deliberate logout-close never loops).\n */\n superviseWakeSocket(\n options: SuperviseWakeOptions,\n timing: WakeSupervisorTiming = DEFAULT_WAKE_TIMING\n ): SupervisedWakeSocketHandle {\n const supervisor = new WakeSocketSupervisor(\n {\n onWake: (wake) => {\n void this.noteSyncEpoch(wake.syncEpoch);\n options.onWake(wake);\n },\n onReconnect: options.onReconnect,\n onStatus: options.onStatus,\n },\n {\n openSocket: () => this.openWakeSocket(),\n // A 4401/expiry close means the bound token is gone — drop the cached\n // JWT so the next ticket mint re-auths (refresh → challenge fallback).\n onAuthGone: () => {\n this.jwt = null;\n },\n setTimeout: (cb, ms) => setTimeout(cb, ms),\n clearTimeout: (h) => clearTimeout(h),\n random: () => Math.random(),\n },\n timing\n );\n supervisor.start();\n return {\n close: () => supervisor.close(),\n get status() {\n return supervisor.currentStatus;\n },\n };\n }\n}\n"],"mappings":";AAwHM,SAAU,QAAQ,GAAU;AAKhC,SACE,aAAa,cACZ,YAAY,OAAO,CAAC,KACnB,EAAE,YAAY,SAAS,gBACvB,uBAAuB,KACvB,EAAE,sBAAsB;AAE9B;AAuCM,SAAU,OACd,OACA,QACA,QAAgB,IAAE;AAElB,QAAM,QAAQ,QAAQ,KAAK;AAC3B,QAAM,MAAM,OAAO;AACnB,QAAM,WAAW,WAAW;AAC5B,MAAI,CAAC,SAAU,YAAY,QAAQ,QAAS;AAC1C,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,QAAQ,WAAW,cAAc,MAAM,KAAK;AAClD,UAAM,MAAM,QAAQ,UAAU,GAAG,KAAK,QAAQ,OAAO,KAAK;AAC1D,UAAM,UAAU,SAAS,wBAAwB,QAAQ,WAAW;AACpE,QAAI,CAAC;AAAO,YAAM,IAAI,UAAU,OAAO;AACvC,UAAM,IAAI,WAAW,OAAO;EAC9B;AACA,SAAO;AACT;AA2DM,SAAU,QAAQ,UAAe,gBAAgB,MAAI;AACzD,MAAI,SAAS;AAAW,UAAM,IAAI,MAAM,kCAAkC;AAC1E,MAAI,iBAAiB,SAAS;AAAU,UAAM,IAAI,MAAM,uCAAuC;AACjG;AAkBM,SAAU,QAAQ,KAAU,UAAa;AAC7C,SAAO,KAAK,QAAW,qBAAqB;AAC5C,QAAM,MAAM,SAAS;AACrB,MAAI,IAAI,SAAS,KAAK;AACpB,UAAM,IAAI,WAAW,sDAAsD,GAAG;EAChF;AACF;AAkDM,SAAU,SAAS,QAA0B;AACjD,WA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AAiC,WAAW,QAAW,GAAG,CAAC;AAC3G,SAAG,UAAU,MAAM,OAAO,IAAI,eAAe,wCAAwC,SAAS,CAAC;AAAA,IACjG,CAAC;AACD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,oBACE,SACA,SAA+B,qBACH;AAC5B,UAAM,aAAa,IAAI;AAAA,MACrB;AAAA,QACE,QAAQ,CAAC,SAAS;AAChB,eAAK,KAAK,cAAc,KAAK,SAAS;AACtC,kBAAQ,OAAO,IAAI;AAAA,QACrB;AAAA,QACA,aAAa,QAAQ;AAAA,QACrB,UAAU,QAAQ;AAAA,MACpB;AAAA,MACA;AAAA,QACE,YAAY,MAAM,KAAK,eAAe;AAAA;AAAA;AAAA,QAGtC,YAAY,MAAM;AAChB,eAAK,MAAM;AAAA,QACb;AAAA,QACA,YAAY,CAAC,IAAI,OAAO,WAAW,IAAI,EAAE;AAAA,QACzC,cAAc,CAAC,MAAM,aAAa,CAAC;AAAA,QACnC,QAAQ,MAAM,KAAK,OAAO;AAAA,MAC5B;AAAA,MACA;AAAA,IACF;AACA,eAAW,MAAM;AACjB,WAAO;AAAA,MACL,OAAO,MAAM,WAAW,MAAM;AAAA,MAC9B,IAAI,SAAS;AACX,eAAO,WAAW;AAAA,MACpB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../node_modules/@noble/hashes/src/utils.ts","../../node_modules/@noble/hashes/src/_md.ts","../../node_modules/@noble/hashes/src/sha2.ts","../../core/crypto.ts","../../core/errors.ts","../../wallet-api/errors.ts","../../wallet-api/challenge.ts","../../wallet-api/codec.ts","../../wallet-api/wake-supervisor.ts","../../wallet-api/client.ts"],"sourcesContent":["/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n: number, title: string = ''): void {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(\n value: TArg<Uint8Array>,\n length?: number,\n title: string = ''\n): TRet<Uint8Array> {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet<Uint8Array>;\n}\n\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h: TArg<CHash>): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1) throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\n\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr: TArg<TypedArray>): TRet<Uint8Array> {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet<Uint8Array>;\n}\n\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr: TArg<TypedArray>): TRet<Uint32Array> {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet<Uint32Array>;\n}\n\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays: TArg<TypedArray[]>): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg<TypedArray>): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr: TArg<Uint32Array>): TRet<Uint32Array> {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr as TRet<Uint32Array>;\n}\n\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array> = isLE\n ? (u: TArg<Uint32Array>) => u as TRet<Uint32Array>\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg<Uint8Array>): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet<Uint8Array> {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet<Uint8Array> {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data: TArg<KDFInput>, errorTitle = ''): TRet<Uint8Array> {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<Uint8Array> {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash<T> {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by `digest()`. */\n outputLen: number;\n /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n canXOF: boolean;\n /**\n * Absorbs more message bytes into the running hash state.\n * @param buf - message chunk to absorb\n * @returns The same hash instance for chaining.\n */\n update(buf: TArg<Uint8Array>): this;\n /**\n * Finalizes the hash into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg<Uint8Array>): void;\n /**\n * Finalizes the hash and returns a freshly allocated digest.\n * @returns Digest bytes.\n */\n digest(): TRet<Uint8Array>;\n /** Wipes internal state and makes the instance unusable. */\n destroy(): void;\n /**\n * Copies the current hash state into an existing or new instance.\n * @param to - Optional destination instance to reuse.\n * @returns Cloned hash state.\n */\n _cloneInto(to?: T): T;\n /**\n * Creates an independent copy of the current hash state.\n * @returns Cloned hash instance.\n */\n clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n /**\n * Mixes more entropy into the generator state.\n * @param seed - fresh entropy bytes\n * @returns Nothing. Implementations update internal state in place.\n */\n addEntropy(seed: TArg<Uint8Array>): void;\n /**\n * Generates pseudorandom output bytes.\n * @param length - number of bytes to generate\n * @returns Generated pseudorandom bytes.\n */\n randomBytes(length: number): TRet<Uint8Array>;\n /** Wipes generator state and makes the instance unusable. */\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n /**\n * Reads more bytes from the XOF stream.\n * @param bytes - number of bytes to read\n * @returns Requested digest bytes.\n */\n xof(bytes: number): TRet<Uint8Array>;\n /**\n * Reads more bytes from the XOF stream into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Filled output buffer.\n */\n xofInto(buf: TArg<Uint8Array>): TRet<Uint8Array>;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n /** DER-encoded object identifier bytes for the hash algorithm. */\n oid?: TRet<Uint8Array>;\n};\n/** Callable hash function type. */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n /** Digest size in bytes. */\n outputLen: number;\n /** Input block size in bytes. */\n blockLen: number;\n /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n canXOF: boolean;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: TArg<Uint8Array>): TRet<Uint8Array>;\n create(): T;\n }\n : {\n (msg: TArg<Uint8Array>, opts?: TArg<Opts>): TRet<Uint8Array>;\n create(opts?: Opts): T;\n });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n hashCons: HasherCons<T, Opts>,\n info: TArg<HashInfo> = {}\n): TRet<CHash<T, Opts>> {\n const hashC: any = (msg: TArg<Uint8Array>, opts?: TArg<Opts>) =>\n hashCons(opts as Opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC) as TRet<CHash<T, Opts>>;\n}\n\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet<Uint8Array> {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix: number): TRet<Required<HashInfo>> => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n abytes,\n aexists,\n aoutput,\n clean,\n createView,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport abstract class HashMD<T extends HashMD<T>> implements Hash<T> {\n // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n // when it can process whole blocks without buffering first.\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly canXOF = false;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: TArg<Uint8Array>): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: TArg<Uint8Array>): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): TRet<Uint8Array> {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet<Uint8Array>;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet<CHash<_SHA256>> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet<CHash<_SHA224>> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet<CHash<_SHA512>> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet<CHash<_SHA384>> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet<CHash<_SHA512_256>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet<CHash<_SHA512_224>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Cryptographic utilities for SDK2\n *\n * Provides BIP39 mnemonic and BIP32 key derivation functions.\n * Platform-independent - no browser-specific APIs.\n */\n\nimport * as bip39 from 'bip39';\nimport CryptoJS from 'crypto-js';\nimport elliptic from 'elliptic';\nimport { SphereError } from './errors';\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst ec = new elliptic.ec('secp256k1');\n\n/** secp256k1 curve order */\nconst CURVE_ORDER = BigInt(\n '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141'\n);\n\n/** Default derivation path for Unicity (BIP44) */\nexport const DEFAULT_DERIVATION_PATH = \"m/44'/0'/0'\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface MasterKey {\n privateKey: string;\n chainCode: string;\n}\n\nexport interface DerivedKey {\n privateKey: string;\n chainCode: string;\n}\n\nexport interface KeyPair {\n privateKey: string;\n publicKey: string;\n}\n\nexport interface AddressInfo extends KeyPair {\n path: string;\n index: number;\n}\n\n// =============================================================================\n// BIP39 Mnemonic Functions\n// =============================================================================\n\n/**\n * Generate a new BIP39 mnemonic phrase\n * @param strength - Entropy bits (128 = 12 words, 256 = 24 words)\n */\nexport function generateMnemonic(strength: 128 | 256 = 128): string {\n return bip39.generateMnemonic(strength);\n}\n\n/**\n * Validate a BIP39 mnemonic phrase\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n return bip39.validateMnemonic(mnemonic);\n}\n\n/**\n * Convert mnemonic to seed (64-byte hex string)\n * @param mnemonic - BIP39 mnemonic phrase\n * @param passphrase - Optional passphrase for additional security\n */\nexport async function mnemonicToSeed(\n mnemonic: string,\n passphrase: string = ''\n): Promise<string> {\n const seedBuffer = await bip39.mnemonicToSeed(mnemonic, passphrase);\n return Buffer.from(seedBuffer).toString('hex');\n}\n\n/**\n * Synchronous version of mnemonicToSeed\n */\nexport function mnemonicToSeedSync(\n mnemonic: string,\n passphrase: string = ''\n): string {\n const seedBuffer = bip39.mnemonicToSeedSync(mnemonic, passphrase);\n return Buffer.from(seedBuffer).toString('hex');\n}\n\n/**\n * Convert mnemonic to entropy (for recovery purposes)\n */\nexport function mnemonicToEntropy(mnemonic: string): string {\n return bip39.mnemonicToEntropy(mnemonic);\n}\n\n/**\n * Convert entropy to mnemonic\n */\nexport function entropyToMnemonic(entropy: string): string {\n return bip39.entropyToMnemonic(entropy);\n}\n\n// =============================================================================\n// BIP32 Key Derivation\n// =============================================================================\n\n/**\n * Generate master key from seed (BIP32 standard)\n * Uses HMAC-SHA512 with key \"Bitcoin seed\"\n */\nexport function generateMasterKey(seedHex: string): MasterKey {\n const I = CryptoJS.HmacSHA512(\n CryptoJS.enc.Hex.parse(seedHex),\n CryptoJS.enc.Utf8.parse('Bitcoin seed')\n ).toString();\n\n const IL = I.substring(0, 64); // Left 32 bytes - master private key\n const IR = I.substring(64); // Right 32 bytes - master chain code\n\n // Validate master key\n const masterKeyBigInt = BigInt('0x' + IL);\n if (masterKeyBigInt === 0n || masterKeyBigInt >= CURVE_ORDER) {\n throw new SphereError('Invalid master key generated', 'VALIDATION_ERROR');\n }\n\n return {\n privateKey: IL,\n chainCode: IR,\n };\n}\n\n/**\n * Derive child key using BIP32 standard\n * @param parentPrivKey - Parent private key (64 hex chars)\n * @param parentChainCode - Parent chain code (64 hex chars)\n * @param index - Child index (>= 0x80000000 for hardened)\n */\nexport function deriveChildKey(\n parentPrivKey: string,\n parentChainCode: string,\n index: number\n): DerivedKey {\n const isHardened = index >= 0x80000000;\n let data: string;\n\n if (isHardened) {\n // Hardened derivation: 0x00 || parentPrivKey || index\n const indexHex = index.toString(16).padStart(8, '0');\n data = '00' + parentPrivKey + indexHex;\n } else {\n // Non-hardened derivation: compressedPubKey || index\n const keyPair = ec.keyFromPrivate(parentPrivKey, 'hex');\n const compressedPubKey = keyPair.getPublic(true, 'hex');\n const indexHex = index.toString(16).padStart(8, '0');\n data = compressedPubKey + indexHex;\n }\n\n // HMAC-SHA512 with chain code as key\n const I = CryptoJS.HmacSHA512(\n CryptoJS.enc.Hex.parse(data),\n CryptoJS.enc.Hex.parse(parentChainCode)\n ).toString();\n\n const IL = I.substring(0, 64); // Left 32 bytes\n const IR = I.substring(64); // Right 32 bytes (new chain code)\n\n // Add IL to parent key mod n (curve order)\n const ilBigInt = BigInt('0x' + IL);\n const parentKeyBigInt = BigInt('0x' + parentPrivKey);\n\n // Check IL is valid (less than curve order)\n if (ilBigInt >= CURVE_ORDER) {\n throw new SphereError('Invalid key: IL >= curve order', 'VALIDATION_ERROR');\n }\n\n const childKeyBigInt = (ilBigInt + parentKeyBigInt) % CURVE_ORDER;\n\n // Check child key is valid (not zero)\n if (childKeyBigInt === 0n) {\n throw new SphereError('Invalid key: child key is zero', 'VALIDATION_ERROR');\n }\n\n const childPrivKey = childKeyBigInt.toString(16).padStart(64, '0');\n\n return {\n privateKey: childPrivKey,\n chainCode: IR,\n };\n}\n\n/**\n * Derive key at a full BIP32/BIP44 path\n * @param masterPrivKey - Master private key\n * @param masterChainCode - Master chain code\n * @param path - BIP44 path like \"m/44'/0'/0'/0/0\"\n */\nexport function deriveKeyAtPath(\n masterPrivKey: string,\n masterChainCode: string,\n path: string\n): DerivedKey {\n const pathParts = path.replace('m/', '').split('/');\n\n let currentKey = masterPrivKey;\n let currentChainCode = masterChainCode;\n\n for (const part of pathParts) {\n const isHardened = part.endsWith(\"'\") || part.endsWith('h');\n const indexStr = part.replace(/['h]$/, '');\n let index = parseInt(indexStr, 10);\n\n if (isHardened) {\n index += 0x80000000; // Add hardened offset\n }\n\n const derived = deriveChildKey(currentKey, currentChainCode, index);\n currentKey = derived.privateKey;\n currentChainCode = derived.chainCode;\n }\n\n return {\n privateKey: currentKey,\n chainCode: currentChainCode,\n };\n}\n\n// =============================================================================\n// Key Pair Operations\n// =============================================================================\n\n/**\n * Get public key from private key\n * @param privateKey - Private key as hex string\n * @param compressed - Return compressed public key (default: true)\n */\nexport function getPublicKey(privateKey: string, compressed: boolean = true): string {\n const keyPair = ec.keyFromPrivate(privateKey, 'hex');\n return keyPair.getPublic(compressed, 'hex');\n}\n\n/**\n * Create key pair from private key\n */\nexport function createKeyPair(privateKey: string): KeyPair {\n return {\n privateKey,\n publicKey: getPublicKey(privateKey),\n };\n}\n\n// =============================================================================\n// Hash Functions\n// =============================================================================\n\n/**\n * Compute SHA256 hash\n */\nexport function sha256(data: string, inputEncoding: 'hex' | 'utf8' = 'hex'): string {\n const parsed =\n inputEncoding === 'hex'\n ? CryptoJS.enc.Hex.parse(data)\n : CryptoJS.enc.Utf8.parse(data);\n return CryptoJS.SHA256(parsed).toString();\n}\n\n/**\n * Compute RIPEMD160 hash\n */\nexport function ripemd160(data: string, inputEncoding: 'hex' | 'utf8' = 'hex'): string {\n const parsed =\n inputEncoding === 'hex'\n ? CryptoJS.enc.Hex.parse(data)\n : CryptoJS.enc.Utf8.parse(data);\n return CryptoJS.RIPEMD160(parsed).toString();\n}\n\n/**\n * Compute HASH160 (SHA256 -> RIPEMD160)\n */\nexport function hash160(data: string): string {\n const sha = sha256(data, 'hex');\n return ripemd160(sha, 'hex');\n}\n\n/**\n * Compute double SHA256\n */\nexport function doubleSha256(data: string, inputEncoding: 'hex' | 'utf8' = 'hex'): string {\n const first = sha256(data, inputEncoding);\n return sha256(first, 'hex');\n}\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Convert hex string to Uint8Array\n */\nexport function hexToBytes(hex: string): Uint8Array {\n const matches = hex.match(/../g);\n if (!matches) {\n return new Uint8Array(0);\n }\n return Uint8Array.from(matches.map((x) => parseInt(x, 16)));\n}\n\n/**\n * Convert Uint8Array to hex string\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Generate random bytes as hex string\n */\nexport function randomBytes(length: number): string {\n const words = CryptoJS.lib.WordArray.random(length);\n return words.toString(CryptoJS.enc.Hex);\n}\n\n// =============================================================================\n// High-Level Functions\n// =============================================================================\n\n/**\n * Generate identity from mnemonic\n * Returns master key derived from mnemonic seed\n */\nexport async function identityFromMnemonic(\n mnemonic: string,\n passphrase: string = ''\n): Promise<MasterKey> {\n if (!validateMnemonic(mnemonic)) {\n throw new SphereError('Invalid mnemonic phrase', 'INVALID_IDENTITY');\n }\n const seedHex = await mnemonicToSeed(mnemonic, passphrase);\n return generateMasterKey(seedHex);\n}\n\n/**\n * Synchronous version of identityFromMnemonic\n */\nexport function identityFromMnemonicSync(\n mnemonic: string,\n passphrase: string = ''\n): MasterKey {\n if (!validateMnemonic(mnemonic)) {\n throw new SphereError('Invalid mnemonic phrase', 'INVALID_IDENTITY');\n }\n const seedHex = mnemonicToSeedSync(mnemonic, passphrase);\n return generateMasterKey(seedHex);\n}\n\n/**\n * Derive key info at a specific path\n * @param masterKey - Master key with privateKey and chainCode\n * @param basePath - Base derivation path (e.g., \"m/44'/0'/0'\")\n * @param index - Address index\n * @param isChange - Whether this is a change address (chain 1 vs 0)\n */\nexport function deriveAddressInfo(\n masterKey: MasterKey,\n basePath: string,\n index: number,\n isChange: boolean = false\n): AddressInfo {\n const chain = isChange ? 1 : 0;\n const fullPath = `${basePath}/${chain}/${index}`;\n\n const derived = deriveKeyAtPath(masterKey.privateKey, masterKey.chainCode, fullPath);\n const publicKey = getPublicKey(derived.privateKey);\n\n return {\n privateKey: derived.privateKey,\n publicKey,\n path: fullPath,\n index,\n };\n}\n\n/**\n * Generate full key info from private key with index and path\n */\nexport function generateAddressInfo(\n privateKey: string,\n index: number,\n path: string\n): AddressInfo {\n const publicKey = getPublicKey(privateKey);\n return {\n privateKey,\n publicKey,\n path,\n index,\n };\n}\n\n/**\n * Generate key info from master private key using HMAC-SHA512 derivation\n * This matches exactly the original index.html implementation\n * NOTE: This is NON-STANDARD derivation for legacy wallet compatibility.\n *\n * Dual-use: in `wif_hmac` derivation mode (legacy wallet import) this derives\n * the wallet's chainPubkey (used for L3 identity).\n *\n * @param masterPrivateKey - 32-byte hex private key (64 chars)\n * @param index - Address index\n */\nexport function generateAddressFromMasterKey(\n masterPrivateKey: string,\n index: number\n): AddressInfo {\n const derivationPath = `m/44'/0'/${index}'`;\n\n // HMAC-SHA512 with path as key (matching index.html exactly)\n const hmacInput = CryptoJS.enc.Hex.parse(masterPrivateKey);\n const hmacKey = CryptoJS.enc.Utf8.parse(derivationPath);\n const hmacOutput = CryptoJS.HmacSHA512(hmacInput, hmacKey).toString();\n\n // Use left 32 bytes for private key\n const childPrivateKey = hmacOutput.substring(0, 64);\n\n return generateAddressInfo(childPrivateKey, index, derivationPath);\n}\n\n// =============================================================================\n// Message Signing (secp256k1 ECDSA with recoverable signature)\n// =============================================================================\n\n/** Prefix prepended to all signed messages (Bitcoin-like signed message format) */\nexport const SIGN_MESSAGE_PREFIX = 'Sphere Signed Message:\\n';\n\n/** Encode an integer as a Bitcoin-style compact varint */\nfunction varint(n: number): Uint8Array {\n if (n < 253) return new Uint8Array([n]);\n const buf = new Uint8Array(3);\n buf[0] = 253;\n buf[1] = n & 0xff;\n buf[2] = (n >> 8) & 0xff;\n return buf;\n}\n\n/**\n * Hash a message for signing using the Bitcoin-like double-SHA256 scheme:\n * SHA256(SHA256(varint(prefix.length) + prefix + varint(msg.length) + msg))\n *\n * @returns 64-char lowercase hex hash\n */\nexport function hashSignMessage(message: string): string {\n const prefix = new TextEncoder().encode(SIGN_MESSAGE_PREFIX);\n const msg = new TextEncoder().encode(message);\n const prefixLen = varint(prefix.length);\n const msgLen = varint(msg.length);\n const full = new Uint8Array(prefixLen.length + prefix.length + msgLen.length + msg.length);\n let off = 0;\n full.set(prefixLen, off); off += prefixLen.length;\n full.set(prefix, off); off += prefix.length;\n full.set(msgLen, off); off += msgLen.length;\n full.set(msg, off);\n const hex = Array.from(full).map(b => b.toString(16).padStart(2, '0')).join('');\n const h1 = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(hex)).toString();\n return CryptoJS.SHA256(CryptoJS.enc.Hex.parse(h1)).toString();\n}\n\n/**\n * Sign a message with a secp256k1 private key.\n *\n * Returns a 130-character hex string: v (2 chars) + r (64 chars) + s (64 chars).\n * The recovery byte `v` is `31 + recoveryParam` (0-3).\n *\n * @param privateKeyHex - 64-char hex private key\n * @param message - plaintext message to sign\n */\nexport function signMessage(privateKeyHex: string, message: string): string {\n const keyPair = ec.keyFromPrivate(privateKeyHex, 'hex');\n const hashHex = hashSignMessage(message);\n const hashBytes = Buffer.from(hashHex, 'hex');\n const sig = keyPair.sign(hashBytes, { canonical: true });\n\n // Find recovery parameter\n const pub = keyPair.getPublic();\n let recoveryParam = -1;\n for (let i = 0; i < 4; i++) {\n try {\n if (ec.recoverPubKey(hashBytes, sig, i).eq(pub)) {\n recoveryParam = i;\n break;\n }\n } catch { /* try next */ }\n }\n if (recoveryParam === -1) {\n throw new SphereError('Could not find recovery parameter', 'SIGNING_ERROR');\n }\n\n const v = (31 + recoveryParam).toString(16).padStart(2, '0');\n const r = sig.r.toString('hex').padStart(64, '0');\n const s = sig.s.toString('hex').padStart(64, '0');\n return v + r + s;\n}\n\n/**\n * Verify a signed message against a compressed secp256k1 public key.\n *\n * @param message - The original plaintext message\n * @param signature - 130-char hex signature (v + r + s)\n * @param expectedPubkey - 66-char compressed public key hex\n * @returns `true` if the signature is valid and matches the expected public key\n */\nexport function verifySignedMessage(\n message: string,\n signature: string,\n expectedPubkey: string,\n): boolean {\n if (signature.length !== 130) return false;\n\n const v = parseInt(signature.slice(0, 2), 16) - 31;\n const r = signature.slice(2, 66);\n const s = signature.slice(66, 130);\n\n if (v < 0 || v > 3) return false;\n\n const hashHex = hashSignMessage(message);\n const hashBytes = Buffer.from(hashHex, 'hex');\n\n try {\n const recovered = ec.recoverPubKey(hashBytes, { r, s }, v);\n const recoveredHex = recovered.encode('hex', true); // compressed\n return recoveredHex === expectedPubkey;\n } catch {\n return false;\n }\n}\n\n/**\n * Recover the compressed secp256k1 public key from a signed message.\n *\n * Use this when the server needs to identify the signer (not just verify\n * a signature against a known pubkey). Combined with `sphere.resolve(pubkey)`\n * it gives a fully cryptographically-attributable identity for backend auth,\n * without trusting any client-supplied identifier claim.\n *\n * @param message - The plaintext that was signed\n * @param signature - 130-char hex (v + r + s) as produced by `signMessage`\n * @returns - Compressed 66-char hex pubkey\n * @throws - On malformed signature length or out-of-range recovery byte\n */\nexport function recoverPubkeyFromSignature(message: string, signature: string): string {\n if (signature.length !== 130) {\n throw new SphereError(\n `Invalid signature length: expected 130 hex chars, got ${signature.length}`,\n 'SIGNING_ERROR',\n );\n }\n\n const v = parseInt(signature.slice(0, 2), 16) - 31;\n const r = signature.slice(2, 66);\n const s = signature.slice(66, 130);\n\n if (v < 0 || v > 3) {\n throw new SphereError(\n `Invalid recovery byte: v=${v} out of range [0..3]`,\n 'SIGNING_ERROR',\n );\n }\n\n const hashHex = hashSignMessage(message);\n const hashBytes = Buffer.from(hashHex, 'hex');\n\n const recovered = ec.recoverPubKey(hashBytes, { r, s }, v);\n return recovered.encode('hex', true);\n}\n\n// Re-export elliptic instance for advanced use cases\nexport { ec };\n","/**\n * SDK Error Types\n *\n * Structured error codes for programmatic error handling in UI.\n * UI can switch on error.code to show appropriate user-facing messages.\n *\n * @example\n * ```ts\n * import { SphereError } from '@unicitylabs/sphere-sdk';\n *\n * try {\n * await sphere.payments.send({ ... });\n * } catch (err) {\n * if (err instanceof SphereError) {\n * switch (err.code) {\n * case 'INSUFFICIENT_BALANCE': showToast('Not enough funds'); break;\n * case 'INVALID_RECIPIENT': showToast('Recipient not found'); break;\n * case 'TRANSPORT_ERROR': showToast('Network connection issue'); break;\n * case 'TIMEOUT': showToast('Request timed out, try again'); break;\n * default: showToast(err.message);\n * }\n * }\n * }\n * ```\n */\n\nexport type SphereErrorCode =\n | 'NOT_INITIALIZED'\n | 'ALREADY_INITIALIZED'\n | 'INVALID_CONFIG'\n | 'INVALID_IDENTITY'\n | 'INSUFFICIENT_BALANCE'\n | 'INVALID_RECIPIENT'\n | 'TRANSFER_FAILED'\n // The source state was consumed by a DIFFERENT transaction (lost race, not a\n // resume) — raised as TransferConflictError (token-engine/errors.ts, Part E.2).\n | 'TRANSFER_CONFLICT'\n | 'STORAGE_ERROR'\n | 'TRANSPORT_ERROR'\n | 'AGGREGATOR_ERROR'\n | 'VALIDATION_ERROR'\n | 'INVALID_AMOUNT'\n | 'NETWORK_ERROR'\n | 'TIMEOUT'\n | 'DECRYPTION_ERROR'\n | 'MODULE_NOT_AVAILABLE'\n | 'SIGNING_ERROR'\n // Token Spend Queue error codes\n | 'SEND_QUEUE_TIMEOUT'\n | 'SEND_INSUFFICIENT_BALANCE'\n | 'SEND_RESERVATION_CANCELLED'\n | 'SEND_QUEUE_FULL'\n | 'MODULE_DESTROYED'\n | 'REENTRANT_GATE'\n // Invoice / Accounting error codes\n | 'INVOICE_NO_TARGETS'\n | 'INVOICE_INVALID_ADDRESS'\n | 'INVOICE_NO_ASSETS'\n | 'INVOICE_INVALID_ASSET'\n | 'INVOICE_INVALID_AMOUNT'\n | 'INVOICE_INVALID_COIN'\n | 'INVOICE_INVALID_NFT'\n | 'INVOICE_PAST_DUE_DATE'\n | 'INVOICE_DUPLICATE_ADDRESS'\n | 'INVOICE_DUPLICATE_COIN'\n | 'INVOICE_DUPLICATE_NFT'\n | 'INVOICE_MINT_FAILED'\n | 'INVOICE_INVALID_PROOF'\n | 'INVOICE_WRONG_TOKEN_TYPE'\n | 'INVOICE_INVALID_DATA'\n | 'INVOICE_ALREADY_EXISTS'\n | 'INVOICE_NOT_FOUND'\n | 'INVOICE_NOT_TARGET'\n | 'INVOICE_ALREADY_CLOSED'\n | 'INVOICE_ALREADY_CANCELLED'\n | 'INVOICE_ORACLE_REQUIRED'\n | 'INVOICE_TERMINATED'\n | 'INVOICE_INVALID_TARGET'\n | 'INVOICE_INVALID_ASSET_INDEX'\n | 'INVOICE_RETURN_EXCEEDS_BALANCE'\n | 'INVOICE_INVALID_DELIVERY_METHOD'\n | 'INVOICE_INVALID_REFUND_ADDRESS'\n | 'INVOICE_INVALID_CONTACT'\n | 'INVOICE_INVALID_ID'\n | 'INVOICE_TOO_MANY_TARGETS'\n | 'INVOICE_TOO_MANY_ASSETS'\n | 'INVOICE_MEMO_TOO_LONG'\n | 'INVOICE_TERMS_TOO_LARGE'\n | 'INVOICE_NOT_TERMINATED'\n | 'INVOICE_NOT_CANCELLED'\n | 'INVOICE_STORAGE_FAILED'\n | 'RATE_LIMITED'\n | 'COMMUNICATIONS_UNAVAILABLE'\n // Swap error codes\n | 'SWAP_INVALID_DEAL'\n | 'SWAP_INVALID_MANIFEST'\n | 'SWAP_NOT_FOUND'\n | 'SWAP_WRONG_STATE'\n | 'SWAP_RESOLVE_FAILED'\n | 'SWAP_DM_SEND_FAILED'\n | 'SWAP_ESCROW_REJECTED'\n | 'SWAP_DEPOSIT_FAILED'\n | 'SWAP_PAYOUT_VERIFICATION_FAILED'\n | 'SWAP_ALREADY_EXISTS'\n | 'SWAP_ALREADY_COMPLETED'\n | 'SWAP_ALREADY_CANCELLED'\n | 'SWAP_TIMEOUT'\n | 'SWAP_LIMIT_EXCEEDED'\n | 'SWAP_ALREADY_INITIALIZED'\n | 'SWAP_MODULE_DESTROYED'\n | 'SWAP_NOT_INITIALIZED';\n\nexport class SphereError extends Error {\n readonly code: SphereErrorCode;\n readonly cause?: unknown;\n\n constructor(message: string, code: SphereErrorCode, cause?: unknown) {\n super(message);\n this.name = 'SphereError';\n this.code = code;\n this.cause = cause;\n }\n}\n\n/**\n * Type guard to check if an error is a SphereError\n */\nexport function isSphereError(err: unknown): err is SphereError {\n return err instanceof SphereError;\n}\n","/**\n * wallet-api/errors.ts — the client's typed error surface (S1).\n *\n * HTTP error mapping follows ARCHITECTURE §16: `{ error: { code, message } }`\n * with 401 auth · 403 ownership/addressee · 404 unknown · 409 conflict\n * (lineage/ownership) · 413 too large · 422 validation · 429 rate-limit/quota.\n */\n\nexport type WalletApiErrorCode =\n /** Construction/config problems (bad base URL, missing identity). */\n | 'CONFIG'\n /** The server challenge failed template verification — never signed. */\n | 'CHALLENGE_TEMPLATE'\n /** 401 — session invalid and re-auth also failed. */\n | 'UNAUTHORIZED'\n /** 403 — ownership/addressee check failed. */\n | 'FORBIDDEN'\n /** 404 — unknown resource. */\n | 'NOT_FOUND'\n /** 409 — lineage/ownership conflict (e.g. evidenced-tombstone re-add — §5.3). */\n | 'CONFLICT'\n /** 413 — blob too large. */\n | 'TOO_LARGE'\n /** 422 — validation failure (malformed body, failed §8.2 pipeline). */\n | 'VALIDATION'\n /** 429 — rate limit / quota. */\n | 'RATE_LIMITED'\n /** Transport-level failure (fetch threw, connection refused, …). */\n | 'NETWORK'\n /** The response did not match the §16 contract (parse/shape failure). */\n | 'PROTOCOL'\n /** Any other non-2xx status. */\n | 'SERVER';\n\nconst STATUS_TO_CODE: Record<number, WalletApiErrorCode> = {\n 401: 'UNAUTHORIZED',\n 403: 'FORBIDDEN',\n 404: 'NOT_FOUND',\n 409: 'CONFLICT',\n 413: 'TOO_LARGE',\n 422: 'VALIDATION',\n 429: 'RATE_LIMITED',\n};\n\nexport class WalletApiError extends Error {\n readonly code: WalletApiErrorCode;\n /** HTTP status when the error came from a response. */\n readonly status?: number;\n\n constructor(message: string, code: WalletApiErrorCode, status?: number, cause?: unknown) {\n super(message);\n this.name = 'WalletApiError';\n this.code = code;\n this.status = status;\n if (cause !== undefined) (this as { cause?: unknown }).cause = cause;\n }\n\n static fromStatus(status: number, message: string): WalletApiError {\n return new WalletApiError(message, STATUS_TO_CODE[status] ?? 'SERVER', status);\n }\n}\n\n/**\n * The auth challenge failed template verification (S1): wrong domain prefix,\n * foreign pubkey, or implausible timestamps. The spend key never signs\n * server-chosen text that fails this check.\n */\nexport class ChallengeTemplateError extends WalletApiError {\n constructor(message: string) {\n super(message, 'CHALLENGE_TEMPLATE');\n this.name = 'ChallengeTemplateError';\n }\n}\n","/**\n * wallet-api/challenge.ts — auth-challenge template verification (S1,\n * ARCHITECTURE §4).\n *\n * The spend key NEVER signs arbitrary server-chosen text. Before signing, the\n * client verifies the challenge:\n * 1. begins with the fixed domain-separation prefix\n * `unicity:wallet-api:auth:v1\\n`;\n * 2. embeds the client's OWN pubkey (and the nonce returned alongside it);\n * 3. carries plausible timestamps (`issuedAt` near now, `expiresAt` in the\n * future, a sane validity window).\n *\n * The accepted grammar matches the REAL backend (wallet-api M1,\n * src/auth/service.ts): the prefix followed by a single-line JSON object with\n * `network`, `pubkey`, `nonce`, `issuedAt`, `expiresAt` (ISO-8601). This\n * grammar is the client's acceptance contract: a server whose challenge does\n * not parse is refused, by design. The fake server\n * (tests/support/fake-wallet-api.ts) produces exactly this form.\n */\n\nimport { ChallengeTemplateError } from './errors';\n\n/** Fixed domain-separation prefix (ARCHITECTURE §4 step 1). */\nexport const AUTH_CHALLENGE_PREFIX = 'unicity:wallet-api:auth:v1\\n';\n\n/** Allowed clock skew between client and server (ms). */\nconst MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;\n\n/** Maximum plausible challenge validity window (server default: NONCE_TTL = 5 min). */\nconst MAX_VALIDITY_WINDOW_MS = 60 * 60 * 1000;\n\nexport interface ChallengeExpectation {\n /** The client's own compressed pubkey hex — the challenge MUST embed it. */\n pubkey: string;\n /** The nonce returned by `POST /v1/auth/challenge` alongside the challenge. */\n nonce: string;\n /** The client's network — refused if the challenge names a different one. */\n network: string;\n /** Current time, ms since epoch. */\n nowMs: number;\n}\n\nfunction parseFields(body: string): Map<string, string> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n throw new ChallengeTemplateError('Challenge body is not the single-line JSON object the backend emits');\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new ChallengeTemplateError('Challenge body must be a JSON object');\n }\n const fields = new Map<string, string>();\n for (const [key, value] of Object.entries(parsed)) {\n if (typeof value !== 'string') {\n throw new ChallengeTemplateError(`Challenge field \"${key}\" must be a string`);\n }\n fields.set(key, value);\n }\n return fields;\n}\n\nfunction requireField(fields: Map<string, string>, key: string): string {\n const value = fields.get(key);\n if (value === undefined || value === '') {\n throw new ChallengeTemplateError(`Challenge is missing the \"${key}\" field`);\n }\n return value;\n}\n\nfunction parseTimestamp(value: string, key: string): number {\n const ms = Date.parse(value);\n if (Number.isNaN(ms)) {\n throw new ChallengeTemplateError(`Challenge \"${key}\" is not a parseable timestamp: ${value}`);\n }\n return ms;\n}\n\n/**\n * Verify a server auth challenge before signing. Throws\n * {@link ChallengeTemplateError} on ANY violation — the caller MUST refuse to\n * sign in that case.\n */\nexport function verifyChallengeTemplate(challenge: string, expect: ChallengeExpectation): void {\n if (typeof challenge !== 'string' || !challenge.startsWith(AUTH_CHALLENGE_PREFIX)) {\n throw new ChallengeTemplateError('Challenge does not start with the unicity:wallet-api:auth:v1 domain prefix');\n }\n const fields = parseFields(challenge.slice(AUTH_CHALLENGE_PREFIX.length));\n\n const pubkey = requireField(fields, 'pubkey');\n if (pubkey.toLowerCase() !== expect.pubkey.toLowerCase()) {\n throw new ChallengeTemplateError('Challenge embeds a different pubkey than this wallet');\n }\n\n const nonce = requireField(fields, 'nonce');\n if (nonce !== expect.nonce) {\n throw new ChallengeTemplateError('Challenge nonce does not match the nonce issued with it');\n }\n\n const network = requireField(fields, 'network');\n if (network !== expect.network) {\n throw new ChallengeTemplateError(`Challenge is for network \"${network}\", expected \"${expect.network}\"`);\n }\n\n const issuedAt = parseTimestamp(requireField(fields, 'issuedAt'), 'issuedAt');\n const expiresAt = parseTimestamp(requireField(fields, 'expiresAt'), 'expiresAt');\n\n if (issuedAt > expect.nowMs + MAX_CLOCK_SKEW_MS) {\n throw new ChallengeTemplateError('Challenge issuedAt is in the future');\n }\n if (expiresAt <= expect.nowMs - MAX_CLOCK_SKEW_MS) {\n throw new ChallengeTemplateError('Challenge is already expired');\n }\n if (expiresAt <= issuedAt || expiresAt - issuedAt > MAX_VALIDITY_WINDOW_MS) {\n throw new ChallengeTemplateError('Challenge validity window is implausible');\n }\n}\n","/**\n * wallet-api/codec.ts — runtime wire ⇄ domain conversion for §16 responses.\n *\n * Hand-rolled validators (repo convention — no zod dependency). The hard rule\n * (ARCHITECTURE §11): asset amounts are decimal strings on the wire and\n * `bigint` in domain types — never a JS `number` (they exceed 2^53). Cursors,\n * seqs and the syncEpoch are parsed the same way; the codec tolerates either\n * a decimal string (the Postgres `bigint`-over-`pg` wire form) or a safe\n * integer number for those counters, but amounts MUST be strings.\n */\n\nimport type { InventoryItem } from '../storage/storage-provider';\nimport { WalletApiError } from './errors';\nimport type {\n BlobUrlEntry,\n CoinBalance,\n HistoryPage,\n HistoryWireRecord,\n IntentRecord,\n InventoryPage,\n MailboxClaimResult,\n MailboxEntry,\n MailboxPage,\n PaymentRequestRecord,\n PaymentRequestsPage,\n UploadUrlEntry,\n} from './types';\n\nfunction protocolError(message: string): WalletApiError {\n return new WalletApiError(message, 'PROTOCOL');\n}\n\nfunction asRecord(value: unknown, what: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw protocolError(`${what} is not an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction asArray(value: unknown, what: string): unknown[] {\n if (!Array.isArray(value)) throw protocolError(`${what} is not an array`);\n return value;\n}\n\nfunction asString(value: unknown, what: string): string {\n if (typeof value !== 'string') throw protocolError(`${what} is not a string`);\n return value;\n}\n\n/** Counter (cursor/seq/syncEpoch): decimal string or safe integer → bigint. */\nexport function parseCounter(value: unknown, what: string): bigint {\n if (typeof value === 'string' && /^[0-9]+$/.test(value)) return BigInt(value);\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return BigInt(value);\n throw protocolError(`${what} is not a non-negative integer counter`);\n}\n\n/** Amount: decimal string ONLY (§11) → bigint. */\nexport function parseAmount(value: unknown, what: string): bigint {\n if (typeof value === 'string' && /^[0-9]+$/.test(value)) return BigInt(value);\n throw protocolError(`${what} is not a decimal-string amount`);\n}\n\nfunction parseAssets(value: unknown, what: string): InventoryItem['assets'] {\n if (value === undefined || value === null) return undefined;\n return asArray(value, what).map((raw, i) => {\n const rec = asRecord(raw, `${what}[${i}]`);\n return {\n coinId: asString(rec.coinId, `${what}[${i}].coinId`),\n amount: parseAmount(rec.amount, `${what}[${i}].amount`),\n };\n });\n}\n\nfunction parseInventoryItem(raw: unknown, what: string): InventoryItem {\n const rec = asRecord(raw, what);\n const status = asString(rec.status, `${what}.status`);\n if (status !== 'active' && status !== 'removed') {\n throw protocolError(`${what}.status is neither 'active' nor 'removed'`);\n }\n return {\n tokenId: asString(rec.tokenId, `${what}.tokenId`),\n status,\n assets: parseAssets(rec.assets, `${what}.assets`),\n seq: parseCounter(rec.seq, `${what}.seq`),\n };\n}\n\n/** `GET /v1/inventory` → {@link InventoryPage} (§16). */\nexport function parseInventoryPage(body: unknown): InventoryPage {\n const rec = asRecord(body, 'inventory response');\n if (typeof rec.more !== 'boolean') throw protocolError('inventory response .more is not a boolean');\n return {\n cursor: parseCounter(rec.cursor, 'inventory response .cursor'),\n syncEpoch: parseCounter(rec.syncEpoch, 'inventory response .syncEpoch'),\n more: rec.more,\n items: asArray(rec.items, 'inventory response .items').map((raw, i) =>\n parseInventoryItem(raw, `items[${i}]`)\n ),\n };\n}\n\n/** `GET /v1/balances` → {@link CoinBalance}[] (§16). */\nexport function parseBalances(body: unknown): CoinBalance[] {\n const rec = asRecord(body, 'balances response');\n return asArray(rec.balances, 'balances response .balances').map((raw, i) => {\n const b = asRecord(raw, `balances[${i}]`);\n const tokenCount = b.tokenCount;\n if (typeof tokenCount !== 'number' || !Number.isSafeInteger(tokenCount) || tokenCount < 0) {\n throw protocolError(`balances[${i}].tokenCount is not a non-negative integer`);\n }\n return {\n coinId: asString(b.coinId, `balances[${i}].coinId`),\n total: parseAmount(b.total, `balances[${i}].total`),\n tokenCount,\n };\n });\n}\n\n/** `POST /v1/tokens/blob-urls` → {@link BlobUrlEntry}[] (§16). */\nexport function parseBlobUrls(body: unknown): BlobUrlEntry[] {\n const rec = asRecord(body, 'blob-urls response');\n return asArray(rec.urls, 'blob-urls response .urls').map((raw, i) => {\n const u = asRecord(raw, `urls[${i}]`);\n return {\n tokenId: asString(u.tokenId, `urls[${i}].tokenId`),\n getUrl: asString(u.getUrl, `urls[${i}].getUrl`),\n };\n });\n}\n\n/** `POST /v1/tokens/upload-urls` → {@link UploadUrlEntry}[] (§16). */\nexport function parseUploadUrls(body: unknown): UploadUrlEntry[] {\n const rec = asRecord(body, 'upload-urls response');\n return asArray(rec.urls, 'upload-urls response .urls').map((raw, i) => {\n const u = asRecord(raw, `urls[${i}]`);\n return {\n sha256: asString(u.sha256, `urls[${i}].sha256`),\n key: asString(u.key, `urls[${i}].key`),\n putUrl: asString(u.putUrl, `urls[${i}].putUrl`),\n };\n });\n}\n\n/** `POST /v1/inventory/apply` → cursor (§16). */\nexport function parseApplyResult(body: unknown): bigint {\n const rec = asRecord(body, 'apply response');\n return parseCounter(rec.cursor, 'apply response .cursor');\n}\n\n/** `GET /v1/intents` → {@link IntentRecord}[] (§16). */\nexport function parseIntents(body: unknown): IntentRecord[] {\n const rec = asRecord(body, 'intents response');\n return asArray(rec.intents, 'intents response .intents').map((raw, i) => {\n const it = asRecord(raw, `intents[${i}]`);\n const status = asString(it.status, `intents[${i}].status`);\n if (status !== 'open' && status !== 'completed' && status !== 'aborted') {\n throw protocolError(`intents[${i}].status is not a known intent status`);\n }\n const createdAt = Date.parse(asString(it.createdAt, `intents[${i}].createdAt`));\n if (Number.isNaN(createdAt)) throw protocolError(`intents[${i}].createdAt is not a timestamp`);\n return {\n transferId: asString(it.transferId, `intents[${i}].transferId`),\n payload: asString(it.payload, `intents[${i}].payload`),\n status,\n createdAt,\n };\n });\n}\n\n// ── mailbox (§6/§16) ──────────────────────────────────────────────────────────\n\n/** `POST /v1/mailbox` → entryId (§16). */\nexport function parseDepositResult(body: unknown): string {\n const rec = asRecord(body, 'mailbox deposit response');\n return asString(rec.entryId, 'mailbox deposit response .entryId');\n}\n\nfunction parseMailboxEntry(raw: unknown, what: string): MailboxEntry {\n const rec = asRecord(raw, what);\n const status = asString(rec.status, `${what}.status`);\n if (status !== 'unclaimed' && status !== 'claimed' && status !== 'rejected') {\n throw protocolError(`${what}.status is not a known mailbox entry status`);\n }\n const createdAt = Date.parse(asString(rec.createdAt, `${what}.createdAt`));\n if (Number.isNaN(createdAt)) throw protocolError(`${what}.createdAt is not a timestamp`);\n return {\n entryId: asString(rec.entryId, `${what}.entryId`),\n seq: parseCounter(rec.seq, `${what}.seq`),\n status,\n transferId: asString(rec.transferId, `${what}.transferId`),\n tokenId: asString(rec.tokenId, `${what}.tokenId`),\n assets: (parseAssets(rec.assets, `${what}.assets`) ?? []).map((a) => ({ ...a })),\n senderPubkey: asString(rec.senderPubkey, `${what}.senderPubkey`),\n ...(rec.memo !== undefined && rec.memo !== null\n ? { memo: asString(rec.memo, `${what}.memo`) }\n : {}),\n createdAt,\n ...(rec.getUrl !== undefined && rec.getUrl !== null\n ? { getUrl: asString(rec.getUrl, `${what}.getUrl`) }\n : {}),\n ...(rec.blobCollected === true ? { blobCollected: true } : {}),\n };\n}\n\n/** `GET /v1/mailbox?since=` → {@link MailboxPage} (§16). */\nexport function parseMailboxPage(body: unknown): MailboxPage {\n const rec = asRecord(body, 'mailbox response');\n if (typeof rec.more !== 'boolean') throw protocolError('mailbox response .more is not a boolean');\n return {\n readPointer: parseCounter(rec.readPointer, 'mailbox response .readPointer'),\n syncEpoch: parseCounter(rec.syncEpoch, 'mailbox response .syncEpoch'),\n more: rec.more,\n entries: asArray(rec.entries, 'mailbox response .entries').map((raw, i) =>\n parseMailboxEntry(raw, `entries[${i}]`)\n ),\n };\n}\n\n/** `POST /v1/mailbox/claim` → {@link MailboxClaimResult} (§16). */\nexport function parseClaimResult(body: unknown): MailboxClaimResult {\n const rec = asRecord(body, 'mailbox claim response');\n return {\n claimed: asArray(rec.claimed, 'claim response .claimed').map((raw, i) =>\n asString(raw, `claimed[${i}]`)\n ),\n alreadyClaimed: asArray(rec.alreadyClaimed, 'claim response .alreadyClaimed').map((raw, i) => {\n const a = asRecord(raw, `alreadyClaimed[${i}]`);\n if (typeof a.intoInventory !== 'boolean') {\n throw protocolError(`alreadyClaimed[${i}].intoInventory is not a boolean`);\n }\n return { entryId: asString(a.entryId, `alreadyClaimed[${i}].entryId`), intoInventory: a.intoInventory };\n }),\n failed: asArray(rec.failed, 'claim response .failed').map((raw, i) => {\n const f = asRecord(raw, `failed[${i}]`);\n return { entryId: asString(f.entryId, `failed[${i}].entryId`), code: asString(f.code, `failed[${i}].code`) };\n }),\n };\n}\n\n/** `POST /v1/mailbox/reject` → rejected entry ids (§16). */\nexport function parseRejectResult(body: unknown): string[] {\n const rec = asRecord(body, 'mailbox reject response');\n return asArray(rec.rejected, 'reject response .rejected').map((raw, i) => asString(raw, `rejected[${i}]`));\n}\n\n// ── payment requests (§10/§16) ────────────────────────────────────────────────\n\n/** One §16 payment request → {@link PaymentRequestRecord} (create/respond/list). */\nexport function parsePaymentRequestRecord(raw: unknown, what: string): PaymentRequestRecord {\n const rec = asRecord(raw, what);\n const status = asString(rec.status, `${what}.status`);\n if (status !== 'open' && status !== 'paid' && status !== 'declined' && status !== 'expired') {\n throw protocolError(`${what}.status is not a known payment-request status`);\n }\n const createdAt = Date.parse(asString(rec.createdAt, `${what}.createdAt`));\n if (Number.isNaN(createdAt)) throw protocolError(`${what}.createdAt is not a timestamp`);\n let expiresAt: number | undefined;\n if (rec.expiresAt !== undefined && rec.expiresAt !== null) {\n expiresAt = Date.parse(asString(rec.expiresAt, `${what}.expiresAt`));\n if (Number.isNaN(expiresAt)) throw protocolError(`${what}.expiresAt is not a timestamp`);\n }\n if (rec.transferId !== null && typeof rec.transferId !== 'string') {\n throw protocolError(`${what}.transferId is neither a string nor null`);\n }\n return {\n id: asString(rec.id, `${what}.id`),\n seq: parseCounter(rec.seq, `${what}.seq`),\n fromPubkey: asString(rec.fromPubkey, `${what}.fromPubkey`),\n toPubkey: asString(rec.toPubkey, `${what}.toPubkey`),\n assets: (parseAssets(rec.assets, `${what}.assets`) ?? []).map((a) => ({ ...a })),\n ...(rec.memo !== undefined && rec.memo !== null\n ? { memo: asString(rec.memo, `${what}.memo`) }\n : {}),\n status,\n transferId: rec.transferId,\n createdAt,\n ...(expiresAt !== undefined ? { expiresAt } : {}),\n };\n}\n\n/**\n * `GET /v1/payment-requests?role=` → {@link PaymentRequestsPage} (§16). The\n * cursor family is role-bound: incoming pages carry the `?since=` seq counter,\n * outgoing pages an opaque keyset string (null once drained) — a page whose\n * cursor does not match its role is a protocol violation.\n */\nexport function parsePaymentRequestsPage(\n body: unknown,\n role: 'incoming' | 'outgoing'\n): PaymentRequestsPage {\n const rec = asRecord(body, 'payment-requests response');\n if (typeof rec.more !== 'boolean') throw protocolError('payment-requests response .more is not a boolean');\n const requests = asArray(rec.requests, 'payment-requests response .requests').map((raw, i) =>\n parsePaymentRequestRecord(raw, `requests[${i}]`)\n );\n const syncEpoch = parseCounter(rec.syncEpoch, 'payment-requests response .syncEpoch');\n if (role === 'incoming') {\n return {\n role,\n requests,\n more: rec.more,\n cursor: parseCounter(rec.cursor, 'payment-requests response .cursor'),\n syncEpoch,\n };\n }\n if (rec.cursor !== null && typeof rec.cursor !== 'string') {\n throw protocolError('payment-requests response .cursor is neither a keyset string nor null');\n }\n return { role, requests, more: rec.more, cursor: rec.cursor, syncEpoch };\n}\n\n// ── history (§10/§16) ─────────────────────────────────────────────────────────\n\nfunction parseHistoryRecord(raw: unknown, what: string): HistoryWireRecord {\n const rec = asRecord(raw, what);\n return {\n dedupKey: asString(rec.dedupKey, `${what}.dedupKey`),\n id: asString(rec.id, `${what}.id`),\n type: asString(rec.type, `${what}.type`),\n ts: asString(rec.ts, `${what}.ts`),\n assets: asArray(rec.assets, `${what}.assets`).map((a, i) => {\n const asset = asRecord(a, `${what}.assets[${i}]`);\n // Amounts stay decimal strings on this surface — display data (§10).\n parseAmount(asset.amount, `${what}.assets[${i}].amount`);\n return {\n coinId: asString(asset.coinId, `${what}.assets[${i}].coinId`),\n amount: asString(asset.amount, `${what}.assets[${i}].amount`),\n };\n }),\n ...(typeof rec.transferId === 'string' ? { transferId: rec.transferId } : {}),\n ...(typeof rec.tokenId === 'string' ? { tokenId: rec.tokenId } : {}),\n ...(typeof rec.counterpartyPubkey === 'string' ? { counterpartyPubkey: rec.counterpartyPubkey } : {}),\n ...(typeof rec.memo === 'string' ? { memo: rec.memo } : {}),\n ...(typeof rec.counterpartyNametag === 'string' ? { counterpartyNametag: rec.counterpartyNametag } : {}),\n };\n}\n\n/** `GET /v1/history` → {@link HistoryPage} (§16). */\nexport function parseHistoryPage(body: unknown): HistoryPage {\n const rec = asRecord(body, 'history response');\n if (typeof rec.more !== 'boolean') throw protocolError('history response .more is not a boolean');\n if (rec.cursor !== null && typeof rec.cursor !== 'string') {\n throw protocolError('history response .cursor is not a string or null');\n }\n return {\n records: asArray(rec.records, 'history response .records').map((raw, i) =>\n parseHistoryRecord(raw, `records[${i}]`)\n ),\n more: rec.more,\n cursor: rec.cursor,\n syncEpoch: parseCounter(rec.syncEpoch, 'history response .syncEpoch'),\n };\n}\n\n/** Auth responses (§4). */\nexport function parseAuthChallenge(body: unknown): { nonce: string; challenge: string } {\n const rec = asRecord(body, 'auth/challenge response');\n return {\n nonce: asString(rec.nonce, 'auth/challenge response .nonce'),\n challenge: asString(rec.challenge, 'auth/challenge response .challenge'),\n };\n}\n\nexport function parseAuthTokens(body: unknown): { jwt: string; refreshToken: string } {\n const rec = asRecord(body, 'auth token response');\n return {\n jwt: asString(rec.jwt, 'auth token response .jwt'),\n refreshToken: asString(rec.refreshToken, 'auth token response .refreshToken'),\n };\n}\n\n/** `POST /v1/ws-ticket` (§9). */\nexport function parseWsTicket(body: unknown): string {\n const rec = asRecord(body, 'ws-ticket response');\n return asString(rec.ticket, 'ws-ticket response .ticket');\n}\n\n/** WS wake frame (§9): `{ type:'wake', stream, syncEpoch }`. */\nexport function parseWakeFrame(raw: string): { stream: 'inventory' | 'mailbox' | 'payment_requests'; syncEpoch: bigint } | null {\n let body: unknown;\n try {\n body = JSON.parse(raw);\n } catch {\n return null;\n }\n if (typeof body !== 'object' || body === null) return null;\n const rec = body as Record<string, unknown>;\n if (rec.type !== 'wake') return null;\n const stream = rec.stream;\n if (stream !== 'inventory' && stream !== 'mailbox' && stream !== 'payment_requests') return null;\n try {\n return { stream, syncEpoch: parseCounter(rec.syncEpoch, 'wake .syncEpoch') };\n } catch {\n return null;\n }\n}\n","/**\n * Wake-socket reconnect supervisor (§9) — makes the single multiplexed wake\n * socket self-heal.\n *\n * The wake socket is a best-effort NUDGE; correctness is the pull. But a\n * SILENTLY dead socket starves every realtime consumer until a reload: the\n * server `terminate()`s on a missed heartbeat, hard-closes at access-token\n * expiry (code 4401), and proxies/idle/network/tab-suspend drop it — none of\n * which the bare `connectWakeSocket` observed once it nulled `onclose`/`onerror`\n * after open.\n *\n * This supervisor keeps `onclose`/`onerror` live and:\n * - reconnects on any drop with bounded exponential backoff + full jitter,\n * re-minting a fresh ticket each attempt (and refreshing the JWT on a 4401 /\n * auth-expiry close) — never giving up while the session is valid;\n * - runs a client-side liveness watchdog: any inbound signal (message, server\n * ping, or pong) is a sign of life; `2×` the server heartbeat of silence\n * means a half-open socket → force-close and reconnect;\n * - runs a full catch-up pull of ALL streams on every (re)connect (`onReconnect`)\n * — wakes missed during the dead window are gone (best-effort pub/sub), so\n * the client MUST full-resync to converge;\n * - distinguishes an intentional close (`destroy`/logout) from a drop so a\n * deliberate 4401 logout-close never spawns an infinite reconnect loop.\n *\n * Lives at the client layer because reconnecting re-mints a ws-ticket and may\n * refresh the JWT — both client-private. The socket OWNER (the MailboxProvider)\n * just supplies the catch-up/wake/status callbacks.\n */\nimport { WalletApiError } from './errors';\nimport { parseWakeFrame } from './codec';\nimport type {\n SuperviseWakeOptions,\n WakeSocketStatus,\n WebSocketLike,\n} from './types';\n\n/** App-defined WS close code: authentication gone — reconnect needs a fresh ticket + token (server `CLOSE_AUTH_GONE`, §9). */\nexport const CLOSE_AUTH_GONE = 4401;\n\nexport interface WakeSupervisorTiming {\n /** First reconnect delay; doubles each attempt up to {@link backoffCapMs}. */\n readonly backoffBaseMs: number;\n /** Backoff ceiling — the delay never exceeds this (before jitter). */\n readonly backoffCapMs: number;\n /**\n * Server heartbeat interval (§9 — 30 s). The liveness watchdog fires after\n * `2×` this of total silence (one whole missed ping/pong cycle + margin).\n */\n readonly heartbeatMs: number;\n}\n\nexport const DEFAULT_WAKE_TIMING: WakeSupervisorTiming = {\n backoffBaseMs: 500,\n backoffCapMs: 30_000,\n heartbeatMs: 30_000,\n};\n\n/** Injectable seams so tests drive time/randomness deterministically. */\nexport interface WakeSupervisorEnv {\n /** Re-mint a ticket and open ONE socket (no auto-reconnect). */\n readonly openSocket: () => Promise<WebSocketLike>;\n /** On a 4401/auth-gone close, drop the cached JWT so the next ticket mint re-auths. */\n readonly onAuthGone: () => void;\n readonly setTimeout: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>;\n readonly clearTimeout: (handle: ReturnType<typeof setTimeout>) => void;\n /** [0,1) — defaults to Math.random; injected for deterministic jitter in tests. */\n readonly random: () => number;\n}\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/**\n * Owns the lifecycle of ONE logical wake channel across reconnects. Construct,\n * call {@link start}, and {@link close} to tear down (idempotent).\n */\nexport class WakeSocketSupervisor {\n private status: WakeSocketStatus = 'connecting';\n private socket: WebSocketLike | null = null;\n private reconnectTimer: Timer | null = null;\n private watchdogTimer: Timer | null = null;\n private attempt = 0;\n private stopped = false;\n /** A reconnect cycle is already scheduled/in-flight — coalesce concurrent drop signals. */\n private reconnecting = false;\n\n constructor(\n private readonly opts: SuperviseWakeOptions,\n private readonly env: WakeSupervisorEnv,\n private readonly timing: WakeSupervisorTiming = DEFAULT_WAKE_TIMING\n ) {}\n\n get currentStatus(): WakeSocketStatus {\n return this.status;\n }\n\n /** Open the first socket; subsequent drops self-heal until {@link close}. */\n start(): void {\n void this.connect();\n }\n\n /** Idempotent teardown — no leaked timers or sockets, and no further reconnects. */\n close(): void {\n if (this.stopped) return;\n this.stopped = true;\n this.clearReconnect();\n this.clearWatchdog();\n this.detachAndClose(this.socket);\n this.socket = null;\n this.setStatus('closed');\n }\n\n // ── connect / drop ──────────────────────────────────────────────────────────\n\n private async connect(): Promise<void> {\n if (this.stopped) return;\n this.clearReconnect();\n try {\n const ws = await this.env.openSocket();\n if (this.stopped) {\n this.detachAndClose(ws);\n return;\n }\n this.adopt(ws);\n } catch (err) {\n if (this.stopped) return;\n // A failed mint/open is just another drop — back off and retry. A 401 in\n // the mint path already triggers the client's silent re-auth, so an\n // auth-expired ticket heals here too.\n this.onDrop(err instanceof WalletApiError && err.status === 401);\n }\n }\n\n /** Wire a freshly opened socket: keep onclose/onerror LIVE, arm the watchdog, run catch-up. */\n private adopt(ws: WebSocketLike): void {\n this.socket = ws;\n this.attempt = 0;\n this.reconnecting = false;\n ws.onmessage = (ev): void => this.onFrame(ev);\n ws.onerror = (): void => this.onDrop(false);\n ws.onclose = (ev): void => this.onClose(ev);\n // Ping/pong (when the transport surfaces them) are pure liveness signals.\n if ('onPing' in ws) ws.onPing = (): void => this.touch();\n if ('onPong' in ws) ws.onPong = (): void => this.touch();\n this.armWatchdog();\n this.setStatus('connected');\n // §9: wakes missed while dark are NOT replayed — full-resync every stream.\n this.opts.onReconnect?.();\n }\n\n private onFrame(ev: { data: unknown }): void {\n this.touch(); // any frame proves the socket is alive\n const frame = parseWakeFrame(typeof ev.data === 'string' ? ev.data : String(ev.data));\n if (frame) this.opts.onWake(frame);\n }\n\n private onClose(ev?: { code?: number }): void {\n this.onDrop(ev?.code === CLOSE_AUTH_GONE);\n }\n\n /** A drop from any cause: schedule a backed-off reconnect (unless intentionally stopped). */\n private onDrop(authGone: boolean): void {\n if (this.stopped) return;\n if (authGone) this.env.onAuthGone(); // force a token refresh on the next mint\n if (this.reconnecting) return; // a reconnect is already queued — don't pile up\n this.reconnecting = true;\n this.clearWatchdog();\n this.detachAndClose(this.socket);\n this.socket = null;\n this.setStatus('reconnecting');\n this.scheduleReconnect();\n }\n\n private scheduleReconnect(): void {\n const delay = this.backoffDelay(this.attempt);\n this.attempt += 1;\n this.reconnectTimer = this.env.setTimeout(() => {\n this.reconnectTimer = null;\n void this.connect();\n }, delay);\n }\n\n /** Exponential `base·2^n` capped at `cap`, then full jitter in `[0, capped]` (thundering-herd guard). */\n private backoffDelay(attempt: number): number {\n const capped = Math.min(this.timing.backoffCapMs, this.timing.backoffBaseMs * 2 ** attempt);\n return Math.floor(this.env.random() * capped);\n }\n\n // ── liveness watchdog ────────────────────────────────────────────────────────\n\n /** Mark the socket alive — re-arm the silence watchdog. */\n private touch(): void {\n if (this.stopped || !this.socket) return;\n this.armWatchdog();\n }\n\n private armWatchdog(): void {\n this.clearWatchdog();\n this.watchdogTimer = this.env.setTimeout(() => {\n this.watchdogTimer = null;\n // Silence for a whole heartbeat cycle ⇒ half-open. Force a reconnect.\n this.onDrop(false);\n }, this.timing.heartbeatMs * 2);\n }\n\n private clearWatchdog(): void {\n if (this.watchdogTimer !== null) {\n this.env.clearTimeout(this.watchdogTimer);\n this.watchdogTimer = null;\n }\n }\n\n private clearReconnect(): void {\n if (this.reconnectTimer !== null) {\n this.env.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n }\n\n /** Detach our handlers (so a late close from THIS socket can't re-trigger) then close it. */\n private detachAndClose(ws: WebSocketLike | null): void {\n if (!ws) return;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n if ('onPing' in ws) ws.onPing = null;\n if ('onPong' in ws) ws.onPong = null;\n try {\n ws.close();\n } catch {\n // already closing/closed — nothing to do\n }\n }\n\n private setStatus(status: WakeSocketStatus): void {\n if (this.status === status) return;\n this.status = status;\n this.opts.onStatus?.(status);\n }\n}\n","/**\n * wallet-api/client.ts — `WalletApiClient` (sdk-changes S1).\n *\n * A small typed client for the wallet-api backend: challenge→sign→JWT with a\n * rotating refresh token, typed REST for the §16 endpoints, and the WS wake\n * channel (ticket flow — §9). Injected into providers (DI; no singletons).\n *\n * Cross-cutting rules (S1):\n * - **Challenge template verification** — the spend key never signs text that\n * fails `verifyChallengeTemplate` (prefix + own pubkey + plausible\n * timestamps). See ./challenge.ts.\n * - **Credential hygiene** — the refresh token lives only in the injected\n * {@link KeyValueStore} (never a URL, never logged). A rotation-reuse\n * revocation or refresh expiry falls back to a fresh challenge→sign cycle —\n * silent, since the wallet key is available at unlock. Non-loopback base\n * URLs MUST be `https:` (ARCHITECTURE §4 transport rule), enforced at\n * construction.\n * - **Amounts are decimal strings end-to-end**, parsed with `BigInt` (§11) —\n * see ./codec.ts.\n *\n * The client also keeps the NORMATIVE LOCAL COPY of open intents (E.3): the\n * server is the primary, but intents are the one server table not\n * re-derivable from blobs — after a server restore (`syncEpoch` change,\n * ARCHITECTURE §5.4) the client re-PUTs its locally-known open intents\n * (idempotent) before anything resumes. `putIntent` persists locally before\n * the server PUT; the local copy survives a failed PUT as the restore\n * backstop.\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { signMessage } from '../core/crypto';\nimport { WalletApiError } from './errors';\nimport { verifyChallengeTemplate } from './challenge';\nimport {\n WakeSocketSupervisor,\n DEFAULT_WAKE_TIMING,\n type WakeSupervisorTiming,\n} from './wake-supervisor';\nimport {\n parseApplyResult,\n parseAuthChallenge,\n parseAuthTokens,\n parseBalances,\n parseBlobUrls,\n parseClaimResult,\n parseDepositResult,\n parseHistoryPage,\n parseIntents,\n parseInventoryPage,\n parseMailboxPage,\n parsePaymentRequestRecord,\n parsePaymentRequestsPage,\n parseRejectResult,\n parseUploadUrls,\n parseWakeFrame,\n parseWsTicket,\n} from './codec';\nimport type {\n ApplyDeltaRequest,\n BlobUrlEntry,\n CoinBalance,\n CreatePaymentRequestInput,\n FetchLike,\n FetchResponseLike,\n HistoryPage,\n HistoryWireRecord,\n IntentRecord,\n InventoryPage,\n KeyValueStore,\n ListPaymentRequestsParams,\n MailboxClaimResult,\n MailboxDepositRequest,\n MailboxPage,\n PaymentRequestRecord,\n PaymentRequestsPage,\n RespondPaymentRequestInput,\n SupervisedWakeSocketHandle,\n SuperviseWakeOptions,\n UploadUrlEntry,\n UploadUrlRequest,\n WakeCallback,\n WakeSocketHandle,\n WalletApiClientConfig,\n WalletApiIdentity,\n WebSocketFactoryLike,\n WebSocketLike,\n} from './types';\n\ninterface LocalIntent {\n payload: string;\n status: 'open' | 'completed' | 'aborted';\n createdAt: number;\n /**\n * #516: set when the abort decision could NOT land on the server (dead\n * backend at send-failure cleanup). {@link WalletApiClient.resyncOpenIntents}\n * replays it (PUT + abort) so the server row converges to aborted instead of\n * resume re-executing a send the user watched fail.\n */\n abortPending?: boolean;\n}\n\nfunction isLoopbackHost(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname.endsWith('.localhost') ||\n /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(hostname) ||\n hostname === '::1' ||\n hostname === '[::1]'\n );\n}\n\n/** Enforce the §4 transport rule: non-loopback MUST be https. */\nfunction assertSecureBaseUrl(baseUrl: string): URL {\n let url: URL;\n try {\n url = new URL(baseUrl);\n } catch {\n throw new WalletApiError(`Invalid wallet-api base URL: ${baseUrl}`, 'CONFIG');\n }\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHost(url.hostname))) {\n throw new WalletApiError(\n 'wallet-api base URL must be https (plain http is allowed only on loopback — ARCHITECTURE §4)',\n 'CONFIG'\n );\n }\n return url;\n}\n\n/** Platform-neutral bytes→base64 (browser btoa + Node ≥16 global btoa). */\nfunction bytesToBase64(bytes: Uint8Array): string {\n let bin = '';\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin);\n}\n\nfunction defaultWebSocketFactory(url: string): import('./types').WebSocketLike {\n const Ctor = (globalThis as { WebSocket?: new (url: string) => import('./types').WebSocketLike }).WebSocket;\n if (!Ctor) {\n throw new WalletApiError(\n 'No global WebSocket available — inject webSocketFactory (e.g. the \"ws\" package on Node < 22)',\n 'CONFIG'\n );\n }\n return new Ctor(url);\n}\n\n/** GET-only retry on a transient NETWORK failure (a dropped/reset connection — e.g. a backend under\n * load resetting mid-read). Total attempts and exponential-backoff base. */\nconst GET_RETRY_ATTEMPTS = 3;\nconst GET_RETRY_BASE_MS = 200;\n\nexport class WalletApiClient {\n /** Network name (also the blob-key prefix `<network>/t/<sha256>` — §5.2). */\n readonly network: string;\n\n private readonly baseUrl: string;\n private readonly deviceId: string;\n private readonly storage: KeyValueStore;\n private readonly fetchFn: FetchLike;\n private readonly wsFactory: WebSocketFactoryLike;\n private readonly now: () => number;\n\n private identity: WalletApiIdentity | null = null;\n private jwt: string | null = null;\n /** Serializes concurrent re-auth attempts. */\n private authInFlight: Promise<void> | null = null;\n /**\n * #583: monotonic auth-session counter. Bumped by every {@link setIdentity}\n * and {@link logout}. A sign-in/refresh attempt captures it at its START and\n * bails before any shared-state mutation (`this.jwt`, the refresh token) if it\n * no longer matches — i.e. the identity moved on while the attempt was async,\n * so its result is stale and would contaminate the new owner. See\n * {@link isStale}.\n */\n private authGeneration = 0;\n\n /** The construction config, retained so {@link clone} can mint a sibling. */\n private readonly config: WalletApiClientConfig;\n\n constructor(config: WalletApiClientConfig) {\n const url = assertSecureBaseUrl(config.baseUrl);\n this.baseUrl = url.toString().replace(/\\/$/, '');\n if (!config.network) throw new WalletApiError('network is required', 'CONFIG');\n this.network = config.network;\n this.deviceId = config.deviceId;\n this.storage = config.storage;\n if (!config.fetchFn && !(globalThis as { fetch?: FetchLike }).fetch) {\n throw new WalletApiError('No fetch available — inject fetchFn', 'CONFIG');\n }\n // Resolve the global lazily THROUGH globalThis so the implementation keeps\n // its original receiver (browser fetch throws \"Illegal invocation\" when\n // called detached).\n this.fetchFn =\n config.fetchFn ?? ((u, init) => (globalThis as unknown as { fetch: FetchLike }).fetch(u, init));\n this.wsFactory = config.webSocketFactory ?? defaultWebSocketFactory;\n this.now = config.now ?? (() => Date.now());\n this.config = config;\n }\n\n /**\n * #583: mint a FRESH, identity-less sibling client from the SAME construction\n * config (baseUrl, network, deviceId, storage, fetch/ws factories, clock).\n * Per-address client isolation builds one client per HD address from this, so\n * each address's providers authenticate as their OWN owner with their OWN JWT\n * — an orphaned previous-address poll pump can never drive a client that has\n * been re-authed to a DIFFERENT owner. The shared `storage` is intentional:\n * its keys are namespaced per (network, chainPubkey, deviceId), so per-owner\n * refresh tokens / cursors stay separate (no cross-owner collision). The clone\n * starts with no identity and no JWT — the caller binds it via setIdentity.\n */\n clone(): WalletApiClient {\n return new WalletApiClient(this.config);\n }\n\n /** Bind the wallet identity this client authenticates as. Resets the session. */\n setIdentity(identity: WalletApiIdentity): void {\n this.identity = identity;\n this.jwt = null;\n // #583: invalidate any in-flight sign-in for the PREVIOUS identity. Nulling\n // `authInFlight` only drops our reference — the orphaned challenge→sign /\n // refresh chain keeps running and could STILL resolve later, at which point\n // it would (a) cache `this.jwt` for the wrong owner and (b) write/clear the\n // refresh token under `refreshTokenKey()`, which is now derived from the NEW\n // identity — cross-owner contamination. Bumping `authGeneration` makes those\n // late mutations self-cancel: every attempt captured the generation at its\n // start and `isStale()`-guards each shared-state write, so a stale chain\n // discards its result instead of clobbering the new owner's session.\n this.authGeneration += 1;\n this.authInFlight = null;\n }\n\n // ── storage keys (scoped per network + pubkey + device) ────────────────────\n\n private requireIdentity(): WalletApiIdentity {\n if (!this.identity) throw new WalletApiError('No identity set — call setIdentity() first', 'CONFIG');\n return this.identity;\n }\n\n private scopedKey(kind: string): string {\n const { chainPubkey } = this.requireIdentity();\n return `wallet-api:${kind}:${this.network}:${chainPubkey}`;\n }\n\n private refreshTokenKey(): string {\n return `${this.scopedKey('refresh')}:${this.deviceId}`;\n }\n\n /**\n * #583: true once the identity has moved on since `gen` was captured (a\n * {@link setIdentity}/{@link logout} bumped {@link authGeneration}). A sign-in\n * attempt checks this before every mutation of `this.jwt` or the refresh token\n * and bails out when stale — its tokens belong to a now-discarded owner.\n */\n private isStale(gen: number): boolean {\n return this.authGeneration !== gen;\n }\n\n // ── auth (ARCHITECTURE §4) ──────────────────────────────────────────────────\n\n /**\n * Establish a session: try the stored refresh token first (rotating), fall\n * back to a fresh challenge→sign→verify cycle. Safe to call repeatedly.\n */\n async signIn(): Promise<void> {\n if (this.authInFlight) return this.authInFlight;\n // #583: bind this attempt to the CURRENT auth generation. A later\n // setIdentity()/logout() bumps the generation; the attempt then self-cancels\n // before mutating shared state (see `signInInner`/`tryRefresh`/`challengeSignIn`).\n const gen = this.authGeneration;\n const inFlight = this.signInInner(gen).finally(() => {\n // #583: only clear the slot if it still holds THIS promise. setIdentity()\n // may null `authInFlight` (abandoning a stale sign-in) and a fresh signIn()\n // may have stored a NEW promise; an unconditional clear here would clobber\n // that newer in-flight sign-in and break the de-dup guarantee.\n if (this.authInFlight === inFlight) this.authInFlight = null;\n });\n this.authInFlight = inFlight;\n return inFlight;\n }\n\n private async signInInner(gen: number): Promise<void> {\n if (await this.tryRefresh(gen)) return;\n // #583: `tryRefresh` returns false for TWO reasons — a genuine refresh miss\n // (no/expired token) OR the identity moved on mid-refresh (`isStale`). In the\n // stale case we must NOT fall through to a challenge→verify cycle: it would\n // run under the NEW owner, hit the network, possibly throw, and be discarded\n // by `challengeSignIn`'s own end-guard anyway. Bail cleanly instead.\n if (this.isStale(gen)) return;\n await this.challengeSignIn(gen);\n }\n\n /**\n * `POST /v1/auth/refresh` with the stored token; rotates on success. Any\n * 4xx (expired, revoked, rotation-reuse revocation) clears the stored token\n * and reports `false` — the caller falls back to a challenge cycle.\n */\n private async tryRefresh(gen: number): Promise<boolean> {\n // #583: capture the refresh-token key NOW. The whole attempt operates on\n // THIS owner's key; a mid-flight identity switch repoints `refreshTokenKey()`\n // at the new owner, so we must never read or write under the new key here.\n const key = this.refreshTokenKey();\n const stored = await this.storage.get(key);\n if (!stored) return false;\n const res = await this.rawFetch('POST', '/v1/auth/refresh', { refreshToken: stored });\n // The identity may have moved on while the request was in flight — discard\n // the result rather than caching the previous owner's JWT / refresh token.\n if (this.isStale(gen)) return false;\n if (res.status === 200) {\n const tokens = parseAuthTokens(await this.readJson(res, 'auth/refresh'));\n this.jwt = tokens.jwt;\n await this.storage.set(key, tokens.refreshToken);\n return true;\n }\n // Stale/revoked/reused token — discard it; a fresh challenge cycle follows.\n await this.storage.remove(key);\n return false;\n }\n\n /** The challenge→verify cycle (§4 steps 1–3) with template verification (S1). */\n private async challengeSignIn(gen: number): Promise<void> {\n const identity = this.requireIdentity();\n // #583: pin the refresh-token key to THIS owner up front (it is derived from\n // the identity); a mid-flight switch must not write under the new owner's key.\n const key = this.refreshTokenKey();\n const challengeRes = await this.rawFetch('POST', '/v1/auth/challenge', {\n pubkey: identity.chainPubkey,\n });\n if (challengeRes.status !== 200) throw await this.toError(challengeRes, 'auth/challenge');\n const { nonce, challenge } = parseAuthChallenge(await this.readJson(challengeRes, 'auth/challenge'));\n\n // The spend key never signs unverified server-chosen text (S1).\n verifyChallengeTemplate(challenge, {\n pubkey: identity.chainPubkey,\n nonce,\n network: this.network,\n nowMs: this.now(),\n });\n\n const signature = signMessage(identity.privateKey, challenge);\n const verifyRes = await this.rawFetch('POST', '/v1/auth/verify', {\n nonce,\n signature,\n deviceId: this.deviceId,\n });\n if (verifyRes.status !== 200) throw await this.toError(verifyRes, 'auth/verify');\n const tokens = parseAuthTokens(await this.readJson(verifyRes, 'auth/verify'));\n // The identity may have switched while challenge→verify was in flight —\n // discard this owner's freshly-minted session instead of caching the JWT /\n // persisting the refresh token under the new owner's storage key.\n if (this.isStale(gen)) return;\n this.jwt = tokens.jwt;\n await this.storage.set(key, tokens.refreshToken);\n }\n\n /** Revoke the session server-side and drop all local credentials. */\n async logout(): Promise<void> {\n // #583: invalidate any in-flight sign-in so it cannot re-cache a JWT or\n // re-persist the refresh token after we have just dropped them.\n this.authGeneration += 1;\n this.authInFlight = null;\n if (this.jwt) {\n try {\n await this.rawFetch('POST', '/v1/auth/logout', {}, this.jwt);\n } finally {\n this.jwt = null;\n }\n }\n await this.storage.remove(this.refreshTokenKey());\n }\n\n // ── request core ────────────────────────────────────────────────────────────\n\n private async rawFetch(\n method: string,\n path: string,\n body?: unknown,\n jwt?: string\n ): Promise<FetchResponseLike> {\n const headers: Record<string, string> = {};\n if (body !== undefined) headers['content-type'] = 'application/json';\n if (jwt) headers['authorization'] = `Bearer ${jwt}`;\n try {\n return await this.fetchFn(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n });\n } catch (err) {\n throw new WalletApiError(`wallet-api request failed: ${method} ${path}`, 'NETWORK', undefined, err);\n }\n }\n\n private async readJson(res: FetchResponseLike, what: string): Promise<unknown> {\n const text = await res.text();\n if (text === '') return null;\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new WalletApiError(`${what}: response is not JSON`, 'PROTOCOL', res.status, err);\n }\n }\n\n private async toError(res: FetchResponseLike, what: string): Promise<WalletApiError> {\n let message = `${what} failed with status ${res.status}`;\n try {\n const body = (await this.readJson(res, what)) as { error?: { code?: string; message?: string } } | null;\n if (body?.error?.message) message = `${what}: ${body.error.code ?? ''} ${body.error.message}`.trim();\n } catch {\n // keep the generic message\n }\n return WalletApiError.fromStatus(res.status, message);\n }\n\n /**\n * GET-only retry on a transient NETWORK failure (a dropped/reset connection — e.g. a backend under\n * load resetting mid-read). GETs are idempotent, so re-issuing is safe; non-GET methods are NEVER\n * retried here because a lost-response retry could double-apply a write. Non-NETWORK outcomes (any\n * HTTP status) come back as a response and are handled by the caller. Bounded exponential backoff.\n */\n private async rawFetchWithReadRetry(\n method: string,\n path: string,\n body: unknown,\n jwt: string\n ): Promise<FetchResponseLike> {\n const attempts = method === 'GET' ? GET_RETRY_ATTEMPTS : 1;\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await this.rawFetch(method, path, body, jwt);\n } catch (err) {\n const transient = err instanceof WalletApiError && err.code === 'NETWORK';\n if (!transient || attempt >= attempts) throw err;\n await new Promise((resolve) => setTimeout(resolve, GET_RETRY_BASE_MS * 2 ** (attempt - 1)));\n }\n }\n }\n\n /**\n * Authenticated JSON request. A 401 triggers one silent re-auth\n * (refresh → challenge fallback) and one retry; idempotent GETs additionally retry a transient\n * NETWORK failure (rawFetchWithReadRetry) so a single dropped connection doesn't fail the call.\n */\n private async requestJson(method: string, path: string, body?: unknown): Promise<unknown> {\n if (!this.jwt) await this.signIn();\n let res = await this.rawFetchWithReadRetry(method, path, body, this.jwt!);\n if (res.status === 401) {\n this.jwt = null;\n await this.signIn();\n res = await this.rawFetchWithReadRetry(method, path, body, this.jwt!);\n }\n if (res.status === 204) return null;\n if (!res.ok) throw await this.toError(res, `${method} ${path}`);\n return this.readJson(res, `${method} ${path}`);\n }\n\n // ── inventory / blobs (§16) ─────────────────────────────────────────────────\n\n /** `GET /v1/inventory?since=` — one page; the caller loops while `more`. */\n async listInventory(since?: bigint): Promise<InventoryPage> {\n const query = since !== undefined ? `?since=${since.toString()}` : '';\n const page = parseInventoryPage(await this.requestJson('GET', `/v1/inventory${query}`));\n await this.noteSyncEpoch(page.syncEpoch);\n return page;\n }\n\n /** `GET /v1/balances` — active rows only. */\n async getBalances(): Promise<CoinBalance[]> {\n return parseBalances(await this.requestJson('GET', '/v1/balances'));\n }\n\n /** `POST /v1/tokens/blob-urls` — owner's active *or tombstoned* rows (§5.3 recovery). */\n async getBlobUrls(tokenIds: string[]): Promise<BlobUrlEntry[]> {\n return parseBlobUrls(await this.requestJson('POST', '/v1/tokens/blob-urls', { tokenIds }));\n }\n\n /** `POST /v1/tokens/upload-urls` — checksum/length-bound presigned PUTs (§5.2). */\n async getUploadUrls(blobs: UploadUrlRequest[]): Promise<UploadUrlEntry[]> {\n return parseUploadUrls(await this.requestJson('POST', '/v1/tokens/upload-urls', { blobs }));\n }\n\n /**\n * `POST /v1/inventory/apply` (§5.3). Also marks the local intent copy\n * completed — the server completes the intent in the same transaction (§16).\n */\n async applyInventoryDelta(req: ApplyDeltaRequest): Promise<bigint> {\n const cursor = parseApplyResult(\n await this.requestJson('POST', '/v1/inventory/apply', {\n transferId: req.transferId,\n spent: req.spent,\n added: req.added,\n ...(req.externalDelivery !== undefined ? { externalDelivery: req.externalDelivery } : {}),\n })\n );\n await this.setLocalIntentStatus(req.transferId, 'completed');\n return cursor;\n }\n\n /** Download blob bytes from a signed GET URL (the URL itself is the credential). */\n async fetchBlob(getUrl: string): Promise<Uint8Array> {\n let res: FetchResponseLike;\n try {\n res = await this.fetchFn(getUrl, { method: 'GET' });\n } catch (err) {\n throw new WalletApiError('blob download failed', 'NETWORK', undefined, err);\n }\n if (!res.ok) throw WalletApiError.fromStatus(res.status, `blob download failed with status ${res.status}`);\n return new Uint8Array(await res.arrayBuffer());\n }\n\n /**\n * Upload blob bytes to a signed PUT URL. A `412 Precondition Failed` means\n * the identical blob already exists (content addressing, `If-None-Match: *`\n * — §5.2) and is treated as success.\n *\n * The §5.2 presign binds `x-amz-checksum-sha256` and `if-none-match` (plus\n * `content-length`) as SIGNED HEADERS — a real S3 endpoint rejects the\n * SigV4 signature unless the uploader sends them verbatim. (Caught by the\n * phase-2 harness on first contact with real MinIO — the in-process fake\n * had only validated the body, not the signed headers.)\n */\n async uploadBlob(putUrl: string, bytes: Uint8Array): Promise<void> {\n let res: FetchResponseLike;\n try {\n res = await this.fetchFn(putUrl, {\n method: 'PUT',\n headers: {\n 'content-type': 'application/octet-stream',\n 'x-amz-checksum-sha256': bytesToBase64(sha256(bytes)),\n 'if-none-match': '*',\n },\n body: bytes,\n });\n } catch (err) {\n throw new WalletApiError('blob upload failed', 'NETWORK', undefined, err);\n }\n if (res.ok || res.status === 412) return;\n throw WalletApiError.fromStatus(res.status, `blob upload failed with status ${res.status}`);\n }\n\n // ── mailbox (§6/§16) ────────────────────────────────────────────────────────\n\n /**\n * `POST /v1/mailbox` — deposit an already-uploaded finished blob to the\n * recipient's mailbox. Idempotent by content-derived `entry_id` (§6): an\n * existing entry in any status returns `200` with its id, provided the\n * request's recipient and key match the stored entry (a mismatch is `409`).\n */\n async depositMailbox(req: MailboxDepositRequest): Promise<string> {\n return parseDepositResult(\n await this.requestJson('POST', '/v1/mailbox', {\n recipientPubkey: req.recipientPubkey,\n key: req.key,\n transferId: req.transferId,\n stateHash: req.stateHash,\n tokenId: req.tokenId,\n ...(req.memo !== undefined ? { memo: req.memo } : {}),\n })\n );\n }\n\n /**\n * `GET /v1/mailbox?since=<seq>` — entries of EVERY status are listable for\n * any client-chosen `since`; a claimed entry carries a working `getUrl`\n * while its blob is within retention, `blobCollected: true` afterwards (§6).\n */\n async listMailbox(since?: bigint): Promise<MailboxPage> {\n const query = since !== undefined ? `?since=${since.toString()}` : '';\n const page = parseMailboxPage(await this.requestJson('GET', `/v1/mailbox${query}`));\n await this.noteSyncEpoch(page.syncEpoch);\n return page;\n }\n\n /**\n * `POST /v1/mailbox/claim` — addressee-only, idempotent ownership handoff\n * (§6). `intoInventory:false` is the delivery-only claim: the entry resolves\n * and the pointer advances with ZERO inventory writes.\n */\n async claimMailbox(entryIds: string[], intoInventory: boolean): Promise<MailboxClaimResult> {\n return parseClaimResult(\n await this.requestJson('POST', '/v1/mailbox/claim', { entryIds, intoInventory })\n );\n }\n\n /**\n * `POST /v1/mailbox/reject` — addressee-only; terminal for DISCOVERY only:\n * the entry counts toward read-pointer contiguity but remains claimable and\n * its blob is retained (§6 — reject is never a destruction path).\n */\n async rejectMailbox(entryIds: string[]): Promise<string[]> {\n return parseRejectResult(await this.requestJson('POST', '/v1/mailbox/reject', { entryIds }));\n }\n\n // ── history (§10/§16) ───────────────────────────────────────────────────────\n\n /**\n * `POST /v1/history` — client-asserted records, deduped by `dedupKey` (the\n * server never writes history rows — §10). `memo`/`counterpartyNametag`\n * MUST already be S6 envelopes.\n */\n async postHistoryRecords(records: HistoryWireRecord[]): Promise<void> {\n await this.requestJson('POST', '/v1/history', { records });\n }\n\n /** `GET /v1/history?before=&limit=` — newest-first keyset pages (§10). */\n async listHistory(options: { before?: string; limit?: number } = {}): Promise<HistoryPage> {\n const params = new URLSearchParams();\n if (options.before !== undefined) params.set('before', options.before);\n if (options.limit !== undefined) params.set('limit', String(options.limit));\n const qs = params.toString();\n return parseHistoryPage(await this.requestJson('GET', `/v1/history${qs ? `?${qs}` : ''}`));\n }\n\n // ── payment requests (§10/§16) ──────────────────────────────────────────────\n\n /**\n * `POST /v1/payment-requests` — create a request addressed to a payer (the\n * payer's account is auto-provisioned even if they never authenticated —\n * §4/§9; the per-payer open cap → 429, §5.5). `memo` MUST already be an S6\n * `enc1.` envelope (§8.3) — only the requester's wallet key decrypts it.\n */\n async createPaymentRequest(input: CreatePaymentRequestInput): Promise<PaymentRequestRecord> {\n return parsePaymentRequestRecord(\n await this.requestJson('POST', '/v1/payment-requests', {\n toPubkey: input.toPubkey,\n // Amounts are decimal strings in every JSON body (§11).\n assets: input.assets.map((a) => ({ coinId: a.coinId, amount: a.amount.toString() })),\n ...(input.memo !== undefined ? { memo: input.memo } : {}),\n ...(input.expiresAt !== undefined ? { expiresAt: new Date(input.expiresAt).toISOString() } : {}),\n }),\n 'payment-request create response'\n );\n }\n\n /**\n * `GET /v1/payment-requests?role=…` (§16): `'incoming'` is the payer's\n * gap-free `?since=<seq>` stream (cursor = bigint, the standard §16 since\n * contract); `'outgoing'` is the requester's newest-first\n * `?before=<opaque keyset>` backfill (cursor = string | null). The two\n * cursor families never mix — the server 422s a mismatched parameter, and\n * the parameter types make it unrepresentable here.\n */\n async listPaymentRequests<R extends 'incoming' | 'outgoing'>(\n params: Extract<ListPaymentRequestsParams, { role: R }>\n ): Promise<Extract<PaymentRequestsPage, { role: R }>> {\n // Widened to the plain union — generic Extract<> members don't narrow.\n const p: ListPaymentRequestsParams = params;\n const query = new URLSearchParams();\n query.set('role', p.role);\n if (p.status !== undefined) query.set('status', p.status);\n if (p.role === 'incoming') {\n if (p.since !== undefined) query.set('since', p.since.toString());\n } else if (p.before !== undefined) {\n query.set('before', p.before);\n }\n const page = parsePaymentRequestsPage(\n await this.requestJson('GET', `/v1/payment-requests?${query.toString()}`),\n p.role\n );\n await this.noteSyncEpoch(page.syncEpoch);\n // The codec already discriminated the page by role; Extract<> re-states\n // the role-bound cursor family to the caller.\n return page as Extract<PaymentRequestsPage, { role: R }>;\n }\n\n /**\n * `POST /v1/payment-requests/{id}/respond` — addressee-only (§10, non-\n * addressee → 403); only an `open` request may be responded to (else 409).\n * `paid` REQUIRES and links the fulfilling send's transferId, `declined`\n * carries none — the pairing is enforced by {@link RespondPaymentRequestInput}.\n */\n async respondPaymentRequest(id: string, response: RespondPaymentRequestInput): Promise<PaymentRequestRecord> {\n return parsePaymentRequestRecord(\n await this.requestJson('POST', `/v1/payment-requests/${id}/respond`, response),\n 'payment-request respond response'\n );\n }\n\n // ── intents (E.3) ───────────────────────────────────────────────────────────\n\n private intentsKey(): string {\n return this.scopedKey('intents');\n }\n\n private async readLocalIntents(): Promise<Record<string, LocalIntent>> {\n const raw = await this.storage.get(this.intentsKey());\n if (!raw) return {};\n try {\n return JSON.parse(raw) as Record<string, LocalIntent>;\n } catch {\n return {};\n }\n }\n\n private async writeLocalIntents(intents: Record<string, LocalIntent>): Promise<void> {\n await this.storage.set(this.intentsKey(), JSON.stringify(intents));\n }\n\n private async setLocalIntentStatus(\n transferId: string,\n status: LocalIntent['status'],\n opts: { abortPending?: boolean } = {}\n ): Promise<void> {\n const intents = await this.readLocalIntents();\n const intent = intents[transferId];\n if (!intent) return;\n if (intent.status === 'completed') return; // completed never reverts (§16)\n const abortPending = opts.abortPending === true;\n if (intent.status === status && (intent.abortPending === true) === abortPending) return;\n intent.status = status;\n if (abortPending) intent.abortPending = true;\n else delete intent.abortPending;\n await this.writeLocalIntents(intents);\n }\n\n /**\n * Persist a (client-encrypted — S6) intent payload: LOCAL copy first, then\n * `PUT /v1/intents/{transferId}` and await the server ack (E.3 — the engine\n * MUST NOT be called before this resolves). A failed server PUT throws, but\n * the local copy stays as the restore backstop and is re-PUT by\n * {@link resyncOpenIntents}.\n */\n async putIntent(transferId: string, payloadEnvelope: string): Promise<void> {\n const intents = await this.readLocalIntents();\n if (!intents[transferId]) {\n intents[transferId] = { payload: payloadEnvelope, status: 'open', createdAt: this.now() };\n await this.writeLocalIntents(intents);\n }\n await this.requestJson('PUT', `/v1/intents/${transferId}`, { payload: payloadEnvelope });\n }\n\n /** `GET /v1/intents?status=` — server-side intent list. */\n async listIntents(status: 'open' | 'aborted'): Promise<IntentRecord[]> {\n return parseIntents(await this.requestJson('GET', `/v1/intents?status=${status}`));\n }\n\n /**\n * `POST /v1/intents/{id}/abort` — soft, recoverable (§16).\n *\n * #516: the LOCAL copy flips to 'aborted' even when the server abort cannot\n * land (dead backend) — leaving it 'open' would make {@link resyncOpenIntents}\n * re-PUT it and the next sign-in's `resumeOpenIntents` RE-EXECUTE a send the\n * user watched fail (and possibly retried manually): a double-pay hazard.\n * An unlanded abort is marked pending and replayed by\n * {@link resyncOpenIntents} (PUT + abort) so the server converges too.\n */\n async abortIntent(transferId: string): Promise<void> {\n try {\n await this.requestJson('POST', `/v1/intents/${transferId}/abort`);\n } catch (err) {\n await this.setLocalIntentStatus(transferId, 'aborted', { abortPending: true });\n throw err;\n }\n await this.setLocalIntentStatus(transferId, 'aborted');\n }\n\n /** `POST /v1/intents/{id}/complete` — the uniform client-side close (E.3). */\n async completeIntent(transferId: string): Promise<void> {\n await this.requestJson('POST', `/v1/intents/${transferId}/complete`);\n await this.setLocalIntentStatus(transferId, 'completed');\n }\n\n /** The locally-known open intents (the E.3 restore backstop). */\n async listLocalOpenIntents(): Promise<IntentRecord[]> {\n const intents = await this.readLocalIntents();\n return Object.entries(intents)\n .filter(([, i]) => i.status === 'open')\n .map(([transferId, i]) => ({ transferId, payload: i.payload, status: 'open' as const, createdAt: i.createdAt }));\n }\n\n /**\n * Re-PUT every locally-known open intent (idempotent — the server PUT is\n * write-once while open/completed). Called after a `syncEpoch` change\n * (server restore — §5.4): intents are the one server table not\n * re-derivable from blobs.\n *\n * #516: also replays locally-aborted intents whose abort never landed on\n * the server (`abortPending`) — PUT (no-op while open/completed; (re)creates\n * the row after a restore or a failed original PUT) then abort, so the\n * server row lands as 'aborted' instead of an 'open' intent that resume\n * would re-execute. Completed-wins is preserved server-side (§16).\n */\n async resyncOpenIntents(): Promise<void> {\n const intents = await this.readLocalIntents();\n for (const [transferId, intent] of Object.entries(intents)) {\n if (intent.status === 'open') {\n await this.requestJson('PUT', `/v1/intents/${transferId}`, { payload: intent.payload });\n } else if (intent.status === 'aborted' && intent.abortPending === true) {\n await this.requestJson('PUT', `/v1/intents/${transferId}`, { payload: intent.payload });\n await this.requestJson('POST', `/v1/intents/${transferId}/abort`);\n await this.setLocalIntentStatus(transferId, 'aborted'); // clears abortPending\n }\n }\n }\n\n // ── syncEpoch (§5.4/§9) ─────────────────────────────────────────────────────\n\n private syncEpochKey(): string {\n return this.scopedKey('syncEpoch');\n }\n\n /**\n * Track the server `syncEpoch` carried by cursor-bearing responses and\n * wakes. On a change (server restore), re-PUT locally-known open intents\n * before anything resumes (E.3). Storage-provider cursor invalidation is\n * the provider's own duty (S2) — it observes the same epoch values.\n */\n private async noteSyncEpoch(epoch: bigint): Promise<void> {\n const stored = await this.storage.get(this.syncEpochKey());\n if (stored === epoch.toString()) return;\n await this.storage.set(this.syncEpochKey(), epoch.toString());\n if (stored !== null) {\n await this.resyncOpenIntents();\n }\n }\n\n // ── realtime (§9) ───────────────────────────────────────────────────────────\n\n /**\n * Open the wake channel: `POST /v1/ws-ticket` (JWT-authed, single-use,\n * short TTL) then `GET /v1/ws?ticket=…` — the JWT never appears in a URL.\n * Wakes are nudges only; correctness comes from the `?since=` cursors.\n */\n async connectWakeSocket(onWake: WakeCallback): Promise<WakeSocketHandle> {\n const ws = await this.openWakeSocket();\n ws.onerror = null;\n ws.onclose = null;\n ws.onmessage = (ev) => {\n const frame = parseWakeFrame(typeof ev.data === 'string' ? ev.data : String(ev.data));\n if (!frame) return;\n void this.noteSyncEpoch(frame.syncEpoch);\n onWake(frame);\n };\n return { close: () => ws.close() };\n }\n\n /**\n * Mint a single-use ticket (a 401 silently re-auths via {@link requestJson}),\n * upgrade to a wake socket and resolve once it opens. ONE socket, no\n * auto-reconnect — the building block reused by {@link connectWakeSocket} and\n * the {@link superviseWakeSocket} supervisor.\n */\n private async openWakeSocket(): Promise<WebSocketLike> {\n const ticket = parseWsTicket(await this.requestJson('POST', '/v1/ws-ticket'));\n const wsBase = this.baseUrl.replace(/^http/, 'ws');\n const ws = this.wsFactory(`${wsBase}/v1/ws?ticket=${encodeURIComponent(ticket)}`);\n await new Promise<void>((resolve, reject) => {\n ws.onopen = () => resolve();\n ws.onerror = (err) => reject(new WalletApiError('wake socket failed to connect', 'NETWORK', undefined, err));\n ws.onclose = () => reject(new WalletApiError('wake socket closed before connecting', 'NETWORK'));\n });\n return ws;\n }\n\n /**\n * Open a SELF-HEALING wake channel (§9): the supervisor keeps the socket\n * alive across drops — bounded backoff + jitter reconnects (fresh ticket each\n * attempt; a 4401/auth-gone close also refreshes the token), a client-side\n * liveness watchdog that force-reconnects a half-open socket, and a full\n * catch-up pull of every stream on each (re)connect (`onReconnect`) so a dead\n * window converges WITHOUT waiting for the poll. `onStatus` surfaces true\n * socket liveness, decoupled from sign-in state. `close()` tears it down with\n * no further reconnects (a deliberate logout-close never loops).\n */\n superviseWakeSocket(\n options: SuperviseWakeOptions,\n timing: WakeSupervisorTiming = DEFAULT_WAKE_TIMING\n ): SupervisedWakeSocketHandle {\n const supervisor = new WakeSocketSupervisor(\n {\n onWake: (wake) => {\n void this.noteSyncEpoch(wake.syncEpoch);\n options.onWake(wake);\n },\n onReconnect: options.onReconnect,\n onStatus: options.onStatus,\n },\n {\n openSocket: () => this.openWakeSocket(),\n // A 4401/expiry close means the bound token is gone — drop the cached\n // JWT so the next ticket mint re-auths (refresh → challenge fallback).\n onAuthGone: () => {\n this.jwt = null;\n },\n setTimeout: (cb, ms) => setTimeout(cb, ms),\n clearTimeout: (h) => clearTimeout(h),\n random: () => Math.random(),\n },\n timing\n );\n supervisor.start();\n return {\n close: () => supervisor.close(),\n get status() {\n return supervisor.currentStatus;\n },\n };\n }\n}\n"],"mappings":";AAwHM,SAAU,QAAQ,GAAU;AAKhC,SACE,aAAa,cACZ,YAAY,OAAO,CAAC,KACnB,EAAE,YAAY,SAAS,gBACvB,uBAAuB,KACvB,EAAE,sBAAsB;AAE9B;AAuCM,SAAU,OACd,OACA,QACA,QAAgB,IAAE;AAElB,QAAM,QAAQ,QAAQ,KAAK;AAC3B,QAAM,MAAM,OAAO;AACnB,QAAM,WAAW,WAAW;AAC5B,MAAI,CAAC,SAAU,YAAY,QAAQ,QAAS;AAC1C,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,QAAQ,WAAW,cAAc,MAAM,KAAK;AAClD,UAAM,MAAM,QAAQ,UAAU,GAAG,KAAK,QAAQ,OAAO,KAAK;AAC1D,UAAM,UAAU,SAAS,wBAAwB,QAAQ,WAAW;AACpE,QAAI,CAAC;AAAO,YAAM,IAAI,UAAU,OAAO;AACvC,UAAM,IAAI,WAAW,OAAO;EAC9B;AACA,SAAO;AACT;AA2DM,SAAU,QAAQ,UAAe,gBA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