@gala-chain/gala-core-sdk 1.0.0 → 1.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +28 -7
  2. package/dist/bridge.cjs +6 -1
  3. package/dist/bridge.cjs.map +1 -1
  4. package/dist/bridge.mjs +7 -2
  5. package/dist/bridge.mjs.map +1 -1
  6. package/dist/browser/bridge.js +1 -1
  7. package/dist/browser/bridge.js.map +1 -1
  8. package/dist/browser/classes/error_catalog.js.map +1 -1
  9. package/dist/browser/classes/error_phase_table.js.map +1 -1
  10. package/dist/browser/classes/error_phases.js.map +1 -1
  11. package/dist/browser/classes/gala_sdk_error.js +1 -1
  12. package/dist/browser/classes/gala_sdk_error.js.map +1 -1
  13. package/dist/browser/classes/signers.js +1 -1
  14. package/dist/browser/classes/signers.js.map +1 -1
  15. package/dist/browser/config/environments.js.map +1 -1
  16. package/dist/browser/index.js +1 -1
  17. package/dist/browser/providers.js.map +1 -1
  18. package/dist/browser/react.js.map +1 -1
  19. package/dist/browser/reads/gateway_reads.js +1 -1
  20. package/dist/browser/reads/gateway_reads.js.map +1 -1
  21. package/dist/browser/reads/parse.js.map +1 -1
  22. package/dist/browser/reads/request.js.map +1 -1
  23. package/dist/browser/reads/types.js.map +1 -1
  24. package/dist/browser/utils/axios_requestor.js.map +1 -1
  25. package/dist/browser/utils/chain_dto_signing.js.map +1 -1
  26. package/dist/browser/utils/class_key.js.map +1 -1
  27. package/dist/browser/utils/dto_operation.js +2 -0
  28. package/dist/browser/utils/dto_operation.js.map +1 -0
  29. package/dist/browser/utils/eip712.js.map +1 -1
  30. package/dist/browser/utils/error_brand.js.map +1 -1
  31. package/dist/browser/utils/eth_address.js.map +1 -1
  32. package/dist/browser/utils/ethers_provider.js.map +1 -1
  33. package/dist/browser/utils/failure_outcomes.js.map +1 -1
  34. package/dist/browser/utils/failure_view.js.map +1 -1
  35. package/dist/browser/utils/fetch_failure.js.map +1 -1
  36. package/dist/browser/utils/pre_send.js +1 -1
  37. package/dist/browser/utils/pre_send.js.map +1 -1
  38. package/dist/browser/utils/signing.js.map +1 -1
  39. package/dist/browser/utils/transport.js +1 -1
  40. package/dist/browser/utils/transport.js.map +1 -1
  41. package/dist/browser/utils/typed_data.js.map +1 -1
  42. package/dist/browser/utils/unique_key.js.map +1 -1
  43. package/dist/browser/utils/unique_key_syntax.js.map +1 -1
  44. package/dist/browser/utils/wallet_keys.js.map +1 -1
  45. package/dist/browser/utils/wallet_rejection.js.map +1 -1
  46. package/dist/browser/version.js +1 -1
  47. package/dist/browser/version.js.map +1 -1
  48. package/dist/browser/wallet.js.map +1 -1
  49. package/dist/browser/writes/gateway_writes.js +1 -1
  50. package/dist/browser/writes/gateway_writes.js.map +1 -1
  51. package/dist/browser/writes/identity.js.map +1 -1
  52. package/dist/browser/writes/lock.js.map +1 -1
  53. package/dist/browser/writes/submit.js +1 -1
  54. package/dist/browser/writes/submit.js.map +1 -1
  55. package/dist/browser/writes/token_ref.js.map +1 -1
  56. package/dist/browser/writes/transfer.js.map +1 -1
  57. package/dist/browser/writes/types.js.map +1 -1
  58. package/dist/index.cjs +119 -8
  59. package/dist/index.cjs.map +1 -1
  60. package/dist/index.d.cts +95 -3
  61. package/dist/index.d.ts +95 -3
  62. package/dist/index.mjs +117 -9
  63. package/dist/index.mjs.map +1 -1
  64. package/package.json +30 -30
  65. /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/defineProperty.js +0 -0
  66. /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPrimitive.js +0 -0
  67. /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPropertyKey.js +0 -0
  68. /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/typeof.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"error_brand.js","names":["GALA_ERROR_BRAND","isRecord","value","hasGalaErrorBrand","isGalaErrorLike","\"code\"","\"params\""],"sources":["../../../src/utils/error_brand.ts"],"sourcesContent":["/**\n * The brand every `GalaSDKError` (and so every product SDK's error) carries, and the duck-type\n * check for the \"failure shape\". This module has NO imports on purpose: it is part of the light\n * `@gala-chain/gala-core-sdk/wallet` entry, which must never pull the error catalog or the main\n * bundle in.\n */\n\n/**\n * The brand of an SDK error: `error[GALA_ERROR_BRAND] === true`. It is a registered symbol\n * (`Symbol.for`), so two copies of the SDK in one page (a wallet bundle and an app bundle) still\n * recognise each other's errors, which `instanceof` cannot do.\n */\nexport const GALA_ERROR_BRAND: unique symbol = Symbol.for('@gala-chain/gala-core-sdk/error');\n\n/** The least an object must have to be read as an SDK error or its plain-object view. */\nexport interface GalaErrorShape {\n readonly code: string;\n readonly params: Readonly<Record<string, unknown>>;\n}\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** True when `value` carries the SDK error brand (a real `GalaSDKError`, from any copy of the SDK). */\nexport function hasGalaErrorBrand(value: unknown): boolean {\n return isRecord(value) && value[GALA_ERROR_BRAND] === true;\n}\n\n/**\n * True when `value` is an SDK error (it carries the brand) or a plain-object VIEW of one: a string\n * `code` and an object `params`, which is the shape of `GalaSDKError` and of the wrapper objects\n * an app builds from one (`{ code, params, status?, phase?, ... }`). A wallet's own error (an\n * EIP-1193 numeric `code`, an ethers error with a string `code` and no `params`) is neither. It\n * says the value has the SDK's shape, not that `code` is a code the SDK knows.\n *\n * @example\n * ```ts\n * if (isGalaErrorLike(error)) report(error.code, error.params); // no `instanceof`, no SDK import\n * ```\n */\nexport function isGalaErrorLike(value: unknown): value is GalaErrorShape {\n if (hasGalaErrorBrand(value)) return true;\n return (\n isRecord(value) &&\n typeof value['code'] === 'string' &&\n isRecord(value['params']) &&\n !Array.isArray(value['params'])\n );\n}\n"],"mappings":"AAYA,MAAaA,EAAkC,OAAO,IAAI,iCAAiC,EAQ3F,SAASC,EAAS,EAAuD,CACvE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAGA,SAAgBC,EAAkB,EAAyB,CACzD,OAAOF,EAASC,CAAK,GAAKA,EAAMF,KAAsB,EACxD,CAcA,SAAgBI,EAAgB,EAAyC,CAEvE,OADID,EAAkBD,CAAK,EAAU,GAEnCD,EAASC,CAAK,GACd,OAAOA,EAAMG,MAAY,UACzBJ,EAASC,EAAMI,MAAS,GACxB,CAAC,MAAM,QAAQJ,EAAMI,MAAS,CAElC"}
1
+ {"version":3,"file":"error_brand.js","names":["GALA_ERROR_BRAND","isRecord","value","hasGalaErrorBrand","isGalaErrorLike","\"code\"","\"params\""],"sources":["../../../src/utils/error_brand.ts"],"sourcesContent":["/**\n * The brand every `GalaSDKError` (and so every product SDK's error) carries, and the duck-type\n * check for the \"failure shape\". This module has NO imports on purpose: it is part of the light\n * `@gala-chain/gala-core-sdk/wallet` entry, which must never pull the error catalog or the main\n * bundle in.\n */\n\n/**\n * The brand of an SDK error: `error[GALA_ERROR_BRAND] === true`. It is a registered symbol\n * (`Symbol.for`), so two copies of the SDK in one page (a wallet bundle and an app bundle) still\n * recognise each other's errors, which `instanceof` cannot do.\n */\nexport const GALA_ERROR_BRAND: unique symbol = Symbol.for('@gala-chain/gala-core-sdk/error');\n\n/** The least an object must have to be read as an SDK error or its plain-object view. */\nexport interface GalaErrorShape {\n readonly code: string;\n readonly params: Readonly<Record<string, unknown>>;\n}\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** True when `value` carries the SDK error brand (a real `GalaSDKError`, from any copy of the SDK). */\nexport function hasGalaErrorBrand(value: unknown): boolean {\n return isRecord(value) && value[GALA_ERROR_BRAND] === true;\n}\n\n/**\n * True when `value` is an SDK error (it carries the brand) or a plain-object VIEW of one: a string\n * `code` and an object `params`, which is the shape of `GalaSDKError` and of the wrapper objects\n * an app builds from one (`{ code, params, status?, phase?, ... }`). A wallet's own error (an\n * EIP-1193 numeric `code`, an ethers error with a string `code` and no `params`) is neither. It\n * says the value has the SDK's shape, not that `code` is a code the SDK knows.\n *\n * @example\n * ```ts\n * if (isGalaErrorLike(error)) report(error.code, error.params); // no `instanceof`, no SDK import\n * ```\n */\nexport function isGalaErrorLike(value: unknown): value is GalaErrorShape {\n if (hasGalaErrorBrand(value)) return true;\n return (\n isRecord(value) &&\n typeof value['code'] === 'string' &&\n isRecord(value['params']) &&\n !Array.isArray(value['params'])\n );\n}\n"],"mappings":"AAYA,MAAaA,EAAkC,OAAO,IAAI,iCAAiC,EAQ3F,SAASC,EAAS,EAAuD,CACvE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAGA,SAAgBC,EAAkB,EAAyB,CACzD,OAAOF,EAASC,CAAK,GAAKA,EAAMF,KAAsB,EACxD,CAcA,SAAgBI,EAAgB,EAAyC,CAEvE,OADID,EAAkBD,CAAK,EAAU,GAEnCD,EAASC,CAAK,GACd,OAAOA,EAAMG,MAAY,UACzBJ,EAASC,EAAMI,MAAS,GACxB,CAAC,MAAM,QAAQJ,EAAMI,MAAS,CAElC,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"eth_address.js","names":["textEncoder","eip55Digits","lower","digits","hash","keccak_256","checksummed","index","nibble","char","hasValidEip55Casing","ACCOUNT_DIGITS","checksumEthereumAddress","value"],"sources":["../../../src/utils/eth_address.ts"],"sourcesContent":["/**\n * EIP-55 for the 40 hex digits of an Ethereum address, on `@noble/hashes` (no ethers): the one\n * place core computes the checksum casing, shared by the typed-data encoder (which refuses a bad\n * mixed-case address) and the gateway writes (which spell an `0x` account as `eth|<checksummed>`).\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\n\nconst textEncoder = new TextEncoder();\n\n/**\n * The EIP-55 casing of 40 hex digits (any case in, no `0x`): a letter is upper-case where the\n * matching nibble of keccak256(lower-case digits) is 8 or more. Byte-identical to ethers'\n * `getAddress(...).slice(2)` for every 40-digit input.\n */\nexport function eip55Digits(digits: string): string {\n const lower = digits.toLowerCase();\n const hash = keccak_256(textEncoder.encode(lower));\n let checksummed = '';\n for (let index = 0; index < lower.length; index += 1) {\n const nibble = ((hash[index >> 1] as number) >> (index % 2 === 0 ? 4 : 0)) & 0xf;\n const char = lower.charAt(index);\n checksummed += nibble >= 8 ? char.toUpperCase() : char;\n }\n return checksummed;\n}\n\n/**\n * True when 40 hex digits carry no checksum (all one case, as EIP-55 allows) or exactly the\n * EIP-55 one. A mixed-case address with any letter in the wrong case is a typo EIP-55 exists to\n * catch, and is refused by every caller.\n */\nexport function hasValidEip55Casing(digits: string): boolean {\n const mixedCase = /[A-F]/u.test(digits) && /[a-f]/u.test(digits);\n return !mixedCase || eip55Digits(digits) === digits;\n}\n\nconst ACCOUNT_DIGITS = /^(?:0x)?([0-9a-fA-F]{40})$/u;\n\n/**\n * An Ethereum account (`0x` plus 40 hex digits, or the 40 digits alone) as `0x` plus its EIP-55\n * checksummed digits, or `undefined` for anything else: another length or character, or a\n * mixed-case spelling whose casing is not the EIP-55 one (a typo EIP-55 exists to catch).\n * Byte-identical to ethers' `getAddress` for every value it accepts.\n *\n * @example\n * ```typescript\n * checksumEthereumAddress('0x70997970c51812dc3a010c7d01b50e0d17dc79c8');\n * // '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'\n * ```\n */\nexport function checksumEthereumAddress(value: string): string | undefined {\n const digits = ACCOUNT_DIGITS.exec(value)?.[1];\n return digits !== undefined && hasValidEip55Casing(digits)\n ? `0x${eip55Digits(digits)}`\n : undefined;\n}\n"],"mappings":"gDAOA,MAAMA,EAAc,IAAI,YAOxB,SAAgBC,EAAY,EAAwB,CAClD,IAAMC,EAAQC,EAAO,YAAY,EAC3BC,EAAOC,EAAWL,EAAY,OAAOE,CAAK,CAAC,EAC7CI,EAAc,GAClB,IAAK,IAAIC,EAAQ,EAAGA,EAAQL,EAAM,OAAQ,GAAS,EAAG,CACpD,IAAMM,EAAWJ,EAAKG,GAAS,KAAkBA,EAAQ,GAAM,EAAI,EAAI,GAAM,GACvEE,EAAOP,EAAM,OAAOK,CAAK,EAC/B,GAAeC,GAAU,EAAIC,EAAK,YAAY,EAAIA,CACpD,CACA,OAAOH,CACT,CAOA,SAAgBI,EAAoB,EAAyB,CAE3D,MAAO,EADW,SAAS,KAAKP,CAAM,GAAK,SAAS,KAAKA,CAAM,IAC1CF,EAAYE,CAAM,IAAMA,CAC/C,CAEA,MAAMQ,EAAiB,8BAcvB,SAAgBC,EAAwB,EAAmC,CACzE,IAAMT,EAASQ,EAAe,KAAKE,CAAK,CAAC,GAAG,GAC5C,OAAOV,IAAW,IAAA,IAAaO,EAAoBP,CAAM,EACrD,KAAKF,EAAYE,CAAM,IACvB,IAAA,EACN"}
1
+ {"version":3,"file":"eth_address.js","names":["textEncoder","eip55Digits","lower","digits","hash","keccak_256","checksummed","index","nibble","char","hasValidEip55Casing","ACCOUNT_DIGITS","checksumEthereumAddress","value"],"sources":["../../../src/utils/eth_address.ts"],"sourcesContent":["/**\n * EIP-55 for the 40 hex digits of an Ethereum address, on `@noble/hashes` (no ethers): the one\n * place core computes the checksum casing, shared by the typed-data encoder (which refuses a bad\n * mixed-case address) and the gateway writes (which spell an `0x` account as `eth|<checksummed>`).\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\n\nconst textEncoder = new TextEncoder();\n\n/**\n * The EIP-55 casing of 40 hex digits (any case in, no `0x`): a letter is upper-case where the\n * matching nibble of keccak256(lower-case digits) is 8 or more. Byte-identical to ethers'\n * `getAddress(...).slice(2)` for every 40-digit input.\n */\nexport function eip55Digits(digits: string): string {\n const lower = digits.toLowerCase();\n const hash = keccak_256(textEncoder.encode(lower));\n let checksummed = '';\n for (let index = 0; index < lower.length; index += 1) {\n const nibble = ((hash[index >> 1] as number) >> (index % 2 === 0 ? 4 : 0)) & 0xf;\n const char = lower.charAt(index);\n checksummed += nibble >= 8 ? char.toUpperCase() : char;\n }\n return checksummed;\n}\n\n/**\n * True when 40 hex digits carry no checksum (all one case, as EIP-55 allows) or exactly the\n * EIP-55 one. A mixed-case address with any letter in the wrong case is a typo EIP-55 exists to\n * catch, and is refused by every caller.\n */\nexport function hasValidEip55Casing(digits: string): boolean {\n const mixedCase = /[A-F]/u.test(digits) && /[a-f]/u.test(digits);\n return !mixedCase || eip55Digits(digits) === digits;\n}\n\nconst ACCOUNT_DIGITS = /^(?:0x)?([0-9a-fA-F]{40})$/u;\n\n/**\n * An Ethereum account (`0x` plus 40 hex digits, or the 40 digits alone) as `0x` plus its EIP-55\n * checksummed digits, or `undefined` for anything else: another length or character, or a\n * mixed-case spelling whose casing is not the EIP-55 one (a typo EIP-55 exists to catch).\n * Byte-identical to ethers' `getAddress` for every value it accepts.\n *\n * @example\n * ```typescript\n * checksumEthereumAddress('0x70997970c51812dc3a010c7d01b50e0d17dc79c8');\n * // '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'\n * ```\n */\nexport function checksumEthereumAddress(value: string): string | undefined {\n const digits = ACCOUNT_DIGITS.exec(value)?.[1];\n return digits !== undefined && hasValidEip55Casing(digits)\n ? `0x${eip55Digits(digits)}`\n : undefined;\n}\n"],"mappings":"A,gDAOA,MAAMA,EAAc,IAAI,YAOxB,SAAgBC,EAAY,EAAwB,CAClD,IAAMC,EAAQC,EAAO,YAAY,EAC3BC,EAAOC,EAAWL,EAAY,OAAOE,CAAK,CAAC,EAC7CI,EAAc,GAClB,IAAK,IAAIC,EAAQ,EAAGA,EAAQL,EAAM,OAAQ,GAAS,EAAG,CACpD,IAAMM,EAAWJ,EAAKG,GAAS,KAAkBA,EAAQ,GAAM,EAAI,EAAI,GAAM,GACvEE,EAAOP,EAAM,OAAOK,CAAK,EAC/B,GAAeC,GAAU,EAAIC,EAAK,YAAY,EAAIA,CACpD,CACA,OAAOH,CACT,CAOA,SAAgBI,EAAoB,EAAyB,CAE3D,MAAO,EADW,SAAS,KAAKP,CAAM,GAAK,SAAS,KAAKA,CAAM,IAC1CF,EAAYE,CAAM,IAAMA,CAC/C,CAEA,MAAMQ,EAAiB,8BAcvB,SAAgBC,EAAwB,EAAmC,CACzE,IAAMT,EAASQ,EAAe,KAAKE,CAAK,CAAC,GAAG,GAC5C,OAAOV,IAAW,IAAA,IAAaO,EAAoBP,CAAM,EACrD,KAAKF,EAAYE,CAAM,IACvB,IAAA,EACN,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"ethers_provider.js","names":["isRecord","value","isTypedDataTypes","fields","field","\"name\"","\"type\"","malformed","GalaSDKError","readTypedDataRequest","raw","params","payload","domain","types","message","stripEip712DomainType","eip1193ProviderFromEthers","connected","provider","method","wallet","options"],"sources":["../../../src/utils/ethers_provider.ts"],"sourcesContent":["import type { BrowserWalletProvider } from '../classes/signers.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { stripEip712DomainType } from './chain_dto_signing.js';\n\n/**\n * The part of an ethers v6 signer (`JsonRpcSigner`, `Wallet`) the adapter calls. Declared\n * structurally, so the SDK takes no dependency on ethers and an ethers object satisfies it as is.\n */\nexport interface EthersLikeSigner {\n signTypedData(\n domain: Record<string, unknown>,\n types: Record<string, Array<{ name: string; type: string }>>,\n value: Record<string, unknown>,\n ): Promise<string>;\n signMessage(message: string): Promise<string>;\n}\n\n/** The part of an ethers v6 provider (`BrowserProvider`) the adapter calls. */\nexport interface EthersLikeProvider {\n getSigner(): Promise<EthersLikeSigner>;\n /** The raw JSON-RPC passthrough (`BrowserProvider.send`). */\n send(method: string, params: unknown[]): Promise<unknown>;\n}\n\n/** Options of {@link eip1193ProviderFromEthers}. */\nexport interface EthersEip1193Options {\n /**\n * Signs a `personal_sign` message when the provider cannot or should not: a wallet SDK that\n * signs through its own object (TrustWallet's `web3Wallet.signMessage`). When set it answers\n * every `personal_sign`, and the provider is not touched for it.\n */\n personalSign?: ((message: string) => Promise<string>) | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isTypedDataTypes(\n value: unknown,\n): value is Record<string, Array<{ name: string; type: string }>> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (fields) =>\n Array.isArray(fields) &&\n fields.every(\n (field) =>\n isRecord(field) &&\n typeof field['name'] === 'string' &&\n typeof field['type'] === 'string',\n ),\n )\n );\n}\n\nfunction malformed(method: string): GalaSDKError {\n return new GalaSDKError('MALFORMED_WALLET_REQUEST', { method });\n}\n\n/** Splits `eth_signTypedData_v4` params (`[account, JSON payload]`) into what ethers' signer takes. */\nfunction readTypedDataRequest(params: unknown[] | undefined): {\n domain: Record<string, unknown>;\n types: Record<string, Array<{ name: string; type: string }>>;\n message: Record<string, unknown>;\n} {\n const raw = params?.[1];\n let payload: unknown;\n try {\n payload = typeof raw === 'string' ? JSON.parse(raw) : raw;\n } catch {\n throw malformed('eth_signTypedData_v4');\n }\n if (!isRecord(payload)) throw malformed('eth_signTypedData_v4');\n const { domain, types, message } = payload;\n if (!isRecord(domain) || !isTypedDataTypes(types) || !isRecord(message)) {\n throw malformed('eth_signTypedData_v4');\n }\n // ethers refuses an explicit EIP712Domain type; the JSON-RPC form includes it.\n return { domain, types: stripEip712DomainType(types), message };\n}\n\n/**\n * An EIP-1193 provider over an ethers v6 provider, for {@link BrowserWalletSigner}: apps whose\n * wallet connection is an ethers `BrowserProvider` sign through the very ethers calls they always\n * made, with no hand-written shim.\n *\n * - `eth_chainId` is `provider.send('eth_chainId', [])`: the wallet's LIVE chain. Never\n * `provider.getNetwork()`, which ethers caches and does not invalidate on `chainChanged`, so a\n * user who switches networks after connecting would sign against a stale chainId.\n * - `eth_signTypedData_v4` parses the `[account, JSON]` params and calls\n * `signer.signTypedData(domain, types, message)` with `EIP712Domain` removed from `types`.\n * - `personal_sign` is `options.personalSign(message)` when given, else `signer.signMessage`.\n * - Anything else is `UNSUPPORTED_WALLET_METHOD`; a malformed request is\n * `MALFORMED_WALLET_REQUEST`; a missing provider is `WALLET_UNAVAILABLE`.\n *\n * `provider` may be `null`/`undefined` (nothing connected): a request that needs it then fails\n * with `WALLET_UNAVAILABLE` rather than at construction, so a signer can be built before the\n * connection state is known.\n *\n * @example\n * ```ts\n * const signer = new BrowserWalletSigner(eip1193ProviderFromEthers(browserProvider), account, {\n * scheme: 'eip712',\n * });\n * ```\n */\nexport function eip1193ProviderFromEthers(\n provider: EthersLikeProvider | null | undefined,\n options: EthersEip1193Options = {},\n): BrowserWalletProvider {\n const connected = (): EthersLikeProvider => {\n if (provider === null || provider === undefined) {\n throw new GalaSDKError('WALLET_UNAVAILABLE', {});\n }\n return provider;\n };\n return {\n request: async ({ method, params }) => {\n switch (method) {\n case 'eth_chainId':\n return connected().send('eth_chainId', []);\n case 'eth_signTypedData_v4': {\n const wallet = connected();\n const { domain, types, message } = readTypedDataRequest(params);\n return (await wallet.getSigner()).signTypedData(domain, types, message);\n }\n case 'personal_sign': {\n const message = params?.[0];\n if (typeof message !== 'string') throw malformed('personal_sign');\n if (options.personalSign !== undefined) return options.personalSign(message);\n return (await connected().getSigner()).signMessage(message);\n }\n default:\n throw new GalaSDKError('UNSUPPORTED_WALLET_METHOD', { method });\n }\n },\n };\n}\n"],"mappings":"2HAkCA,SAASA,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CAEA,SAASC,EACP,EACgE,CAChE,OACEF,EAASC,CAAK,GACd,OAAO,OAAOA,CAAK,CAAC,CAAC,MAClB,GACC,MAAM,QAAQE,CAAM,GACpBA,EAAO,MACJ,GACCH,EAASI,CAAK,GACd,OAAOA,EAAMC,MAAY,UACzB,OAAOD,EAAME,MAAY,QAC7B,CACJ,CAEJ,CAEA,SAASC,EAAU,EAA8B,CAC/C,OAAO,IAAIC,EAAa,2BAA4B,CAAE,QAAO,CAAC,CAChE,CAGA,SAASC,EAAqB,EAI5B,CACA,IAAMC,EAAMC,IAAS,GACjBC,EACJ,GAAI,CACF,EAAU,OAAOF,GAAQ,SAAW,KAAK,MAAMA,CAAG,EAAIA,CACxD,MAAQ,CACN,MAAMH,EAAU,sBAAsB,CACxC,CACA,GAAI,CAACP,EAASY,CAAO,EAAG,MAAML,EAAU,sBAAsB,EAC9D,GAAM,CAAE,SAAQ,QAAO,WAAYK,EACnC,GAAI,CAACZ,EAASa,CAAM,GAAK,CAACX,EAAiBY,CAAK,GAAK,CAACd,EAASe,CAAO,EACpE,MAAMR,EAAU,sBAAsB,EAGxC,MAAO,CAAE,SAAQ,MAAOS,EAAsBF,CAAK,EAAG,SAAQ,CAChE,CA2BA,SAAgBG,EACd,EACA,EAAgC,CAAC,EACV,CACvB,IAAMC,MAAsC,CAC1C,GAAIC,GAAa,KACf,MAAM,IAAIX,EAAa,qBAAsB,CAAC,CAAC,EAEjD,OAAOW,CACT,EACA,MAAO,CACL,QAAS,MAAO,CAAE,SAAQ,YAAa,CACrC,OAAQC,EAAR,CACE,IAAK,cACH,OAAOF,EAAU,CAAC,CAAC,KAAK,cAAe,CAAC,CAAC,EAC3C,IAAK,uBAAwB,CAC3B,IAAMG,EAASH,EAAU,EACnB,CAAE,SAAQ,QAAO,WAAYT,EAAqBE,CAAM,EAC9D,OAAQ,MAAMU,EAAO,UAAU,EAAA,CAAG,cAAcR,EAAQC,EAAOC,CAAO,CACxE,CACA,IAAK,gBAAiB,CACpB,IAAMA,EAAUJ,IAAS,GACzB,GAAI,OAAOI,GAAY,SAAU,MAAMR,EAAU,eAAe,EAEhE,OADIe,EAAQ,eAAiB,IAAA,IACrB,MAAMJ,EAAU,CAAC,CAAC,UAAU,EAAA,CAAG,YAAYH,CAAO,EADXO,EAAQ,aAAaP,CAAO,CAE7E,CACA,QACE,MAAM,IAAIP,EAAa,4BAA6B,CAAE,QAAO,CAAC,CAClE,CACF,CACF,CACF"}
1
+ {"version":3,"file":"ethers_provider.js","names":["isRecord","value","isTypedDataTypes","fields","field","\"name\"","\"type\"","malformed","GalaSDKError","readTypedDataRequest","raw","params","payload","domain","types","message","stripEip712DomainType","eip1193ProviderFromEthers","connected","provider","method","wallet","options"],"sources":["../../../src/utils/ethers_provider.ts"],"sourcesContent":["import type { BrowserWalletProvider } from '../classes/signers.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { stripEip712DomainType } from './chain_dto_signing.js';\n\n/**\n * The part of an ethers v6 signer (`JsonRpcSigner`, `Wallet`) the adapter calls. Declared\n * structurally, so the SDK takes no dependency on ethers and an ethers object satisfies it as is.\n */\nexport interface EthersLikeSigner {\n signTypedData(\n domain: Record<string, unknown>,\n types: Record<string, Array<{ name: string; type: string }>>,\n value: Record<string, unknown>,\n ): Promise<string>;\n signMessage(message: string): Promise<string>;\n}\n\n/** The part of an ethers v6 provider (`BrowserProvider`) the adapter calls. */\nexport interface EthersLikeProvider {\n getSigner(): Promise<EthersLikeSigner>;\n /** The raw JSON-RPC passthrough (`BrowserProvider.send`). */\n send(method: string, params: unknown[]): Promise<unknown>;\n}\n\n/** Options of {@link eip1193ProviderFromEthers}. */\nexport interface EthersEip1193Options {\n /**\n * Signs a `personal_sign` message when the provider cannot or should not: a wallet SDK that\n * signs through its own object (TrustWallet's `web3Wallet.signMessage`). When set it answers\n * every `personal_sign`, and the provider is not touched for it.\n */\n personalSign?: ((message: string) => Promise<string>) | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isTypedDataTypes(\n value: unknown,\n): value is Record<string, Array<{ name: string; type: string }>> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (fields) =>\n Array.isArray(fields) &&\n fields.every(\n (field) =>\n isRecord(field) &&\n typeof field['name'] === 'string' &&\n typeof field['type'] === 'string',\n ),\n )\n );\n}\n\nfunction malformed(method: string): GalaSDKError {\n return new GalaSDKError('MALFORMED_WALLET_REQUEST', { method });\n}\n\n/** Splits `eth_signTypedData_v4` params (`[account, JSON payload]`) into what ethers' signer takes. */\nfunction readTypedDataRequest(params: unknown[] | undefined): {\n domain: Record<string, unknown>;\n types: Record<string, Array<{ name: string; type: string }>>;\n message: Record<string, unknown>;\n} {\n const raw = params?.[1];\n let payload: unknown;\n try {\n payload = typeof raw === 'string' ? JSON.parse(raw) : raw;\n } catch {\n throw malformed('eth_signTypedData_v4');\n }\n if (!isRecord(payload)) throw malformed('eth_signTypedData_v4');\n const { domain, types, message } = payload;\n if (!isRecord(domain) || !isTypedDataTypes(types) || !isRecord(message)) {\n throw malformed('eth_signTypedData_v4');\n }\n // ethers refuses an explicit EIP712Domain type; the JSON-RPC form includes it.\n return { domain, types: stripEip712DomainType(types), message };\n}\n\n/**\n * An EIP-1193 provider over an ethers v6 provider, for {@link BrowserWalletSigner}: apps whose\n * wallet connection is an ethers `BrowserProvider` sign through the very ethers calls they always\n * made, with no hand-written shim.\n *\n * - `eth_chainId` is `provider.send('eth_chainId', [])`: the wallet's LIVE chain. Never\n * `provider.getNetwork()`, which ethers caches and does not invalidate on `chainChanged`, so a\n * user who switches networks after connecting would sign against a stale chainId.\n * - `eth_signTypedData_v4` parses the `[account, JSON]` params and calls\n * `signer.signTypedData(domain, types, message)` with `EIP712Domain` removed from `types`.\n * - `personal_sign` is `options.personalSign(message)` when given, else `signer.signMessage`.\n * - Anything else is `UNSUPPORTED_WALLET_METHOD`; a malformed request is\n * `MALFORMED_WALLET_REQUEST`; a missing provider is `WALLET_UNAVAILABLE`.\n *\n * `provider` may be `null`/`undefined` (nothing connected): a request that needs it then fails\n * with `WALLET_UNAVAILABLE` rather than at construction, so a signer can be built before the\n * connection state is known.\n *\n * @example\n * ```ts\n * const signer = new BrowserWalletSigner(eip1193ProviderFromEthers(browserProvider), account, {\n * scheme: 'eip712',\n * });\n * ```\n */\nexport function eip1193ProviderFromEthers(\n provider: EthersLikeProvider | null | undefined,\n options: EthersEip1193Options = {},\n): BrowserWalletProvider {\n const connected = (): EthersLikeProvider => {\n if (provider === null || provider === undefined) {\n throw new GalaSDKError('WALLET_UNAVAILABLE', {});\n }\n return provider;\n };\n return {\n request: async ({ method, params }) => {\n switch (method) {\n case 'eth_chainId':\n return connected().send('eth_chainId', []);\n case 'eth_signTypedData_v4': {\n const wallet = connected();\n const { domain, types, message } = readTypedDataRequest(params);\n return (await wallet.getSigner()).signTypedData(domain, types, message);\n }\n case 'personal_sign': {\n const message = params?.[0];\n if (typeof message !== 'string') throw malformed('personal_sign');\n if (options.personalSign !== undefined) return options.personalSign(message);\n return (await connected().getSigner()).signMessage(message);\n }\n default:\n throw new GalaSDKError('UNSUPPORTED_WALLET_METHOD', { method });\n }\n },\n };\n}\n"],"mappings":"A,2HAkCA,SAASA,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CAEA,SAASC,EACP,EACgE,CAChE,OACEF,EAASC,CAAK,GACd,OAAO,OAAOA,CAAK,CAAC,CAAC,MAClB,GACC,MAAM,QAAQE,CAAM,GACpBA,EAAO,MACJ,GACCH,EAASI,CAAK,GACd,OAAOA,EAAMC,MAAY,UACzB,OAAOD,EAAME,MAAY,QAC7B,CACJ,CAEJ,CAEA,SAASC,EAAU,EAA8B,CAC/C,OAAO,IAAIC,EAAa,2BAA4B,CAAE,QAAO,CAAC,CAChE,CAGA,SAASC,EAAqB,EAI5B,CACA,IAAMC,EAAMC,IAAS,GACjBC,EACJ,GAAI,CACF,EAAU,OAAOF,GAAQ,SAAW,KAAK,MAAMA,CAAG,EAAIA,CACxD,MAAQ,CACN,MAAMH,EAAU,sBAAsB,CACxC,CACA,GAAI,CAACP,EAASY,CAAO,EAAG,MAAML,EAAU,sBAAsB,EAC9D,GAAM,CAAE,SAAQ,QAAO,WAAYK,EACnC,GAAI,CAACZ,EAASa,CAAM,GAAK,CAACX,EAAiBY,CAAK,GAAK,CAACd,EAASe,CAAO,EACpE,MAAMR,EAAU,sBAAsB,EAGxC,MAAO,CAAE,SAAQ,MAAOS,EAAsBF,CAAK,EAAG,SAAQ,CAChE,CA2BA,SAAgBG,EACd,EACA,EAAgC,CAAC,EACV,CACvB,IAAMC,MAAsC,CAC1C,GAAIC,GAAa,KACf,MAAM,IAAIX,EAAa,qBAAsB,CAAC,CAAC,EAEjD,OAAOW,CACT,EACA,MAAO,CACL,QAAS,MAAO,CAAE,SAAQ,YAAa,CACrC,OAAQC,EAAR,CACE,IAAK,cACH,OAAOF,EAAU,CAAC,CAAC,KAAK,cAAe,CAAC,CAAC,EAC3C,IAAK,uBAAwB,CAC3B,IAAMG,EAASH,EAAU,EACnB,CAAE,SAAQ,QAAO,WAAYT,EAAqBE,CAAM,EAC9D,OAAQ,MAAMU,EAAO,UAAU,EAAA,CAAG,cAAcR,EAAQC,EAAOC,CAAO,CACxE,CACA,IAAK,gBAAiB,CACpB,IAAMA,EAAUJ,IAAS,GACzB,GAAI,OAAOI,GAAY,SAAU,MAAMR,EAAU,eAAe,EAEhE,OADIe,EAAQ,eAAiB,IAAA,IACrB,MAAMJ,EAAU,CAAC,CAAC,UAAU,EAAA,CAAG,YAAYH,CAAO,EADXO,EAAQ,aAAaP,CAAO,CAE7E,CACA,QACE,MAAM,IAAIP,EAAa,4BAA6B,CAAE,QAAO,CAAC,CAClE,CACF,CACF,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"failure_outcomes.js","names":["FAILURE_OUTCOMES"],"sources":["../../../src/utils/failure_outcomes.ts"],"sourcesContent":["/**\n * What a failure means for the operation that raised it, as one vocabulary for every app.\n *\n * - `rejected`: the CHAIN refused the request (a definite no). Nothing was applied, so a NEW\n * request is safe.\n * - `unknown`: the request MAY have been applied (a timeout, a broken connection, an\n * acknowledgement that proves nothing, a failed confirmation). Never submit again under a fresh\n * key: keep `error.uniqueKey` and confirm it.\n * - `not_queued`: the gateway refused the write before queueing it. Nothing is pending.\n * - `not_sent`: the request never left (`error.phase === 'pre_send'`) for a reason outside the\n * call itself: the signer or the wallet failed (locked, unreachable, the person declined), the\n * key provider or the token resolver failed, or no key was available yet. Nothing is pending and\n * nothing was transmitted, so repeating the call is safe and may succeed once the cause (an\n * unlocked wallet) is gone.\n * - `invalid_input`: the call itself cannot work (a bad argument, a missing signer or wallet, an\n * unknown token or pool, a corrupt stored key). Repeating the same call fails the same way.\n * Such an error is also pre-send (`isPreSendError`), but the input is what has to change.\n * - `transient`: a read or connection failed with no state change. Repeating the same call is safe\n * and may succeed.\n *\n * This module has no imports: the failure view (`FailureView.outcome`) and the classifier both\n * read the closed set from here.\n */\nexport const FAILURE_OUTCOMES = [\n 'rejected',\n 'unknown',\n 'not_queued',\n 'not_sent',\n 'invalid_input',\n 'transient',\n] as const;\n\n/** One member of {@link FAILURE_OUTCOMES}. */\nexport type FailureOutcome = (typeof FAILURE_OUTCOMES)[number];\n"],"mappings":"AAuBA,MAAaA,EAAmB,CAC9B,WACA,UACA,aACA,WACA,gBACA,WACF"}
1
+ {"version":3,"file":"failure_outcomes.js","names":["FAILURE_OUTCOMES"],"sources":["../../../src/utils/failure_outcomes.ts"],"sourcesContent":["/**\n * What a failure means for the operation that raised it, as one vocabulary for every app.\n *\n * - `rejected`: the CHAIN refused the request (a definite no). Nothing was applied, so a NEW\n * request is safe.\n * - `unknown`: the request MAY have been applied (a timeout, a broken connection, an\n * acknowledgement that proves nothing, a failed confirmation). Never submit again under a fresh\n * key: keep `error.uniqueKey` and confirm it.\n * - `not_queued`: the gateway refused the write before queueing it. Nothing is pending.\n * - `not_sent`: the request never left (`error.phase === 'pre_send'`) for a reason outside the\n * call itself: the signer or the wallet failed (locked, unreachable, the person declined), the\n * key provider or the token resolver failed, or no key was available yet. Nothing is pending and\n * nothing was transmitted, so repeating the call is safe and may succeed once the cause (an\n * unlocked wallet) is gone.\n * - `invalid_input`: the call itself cannot work (a bad argument, a missing signer or wallet, an\n * unknown token or pool, a corrupt stored key). Repeating the same call fails the same way.\n * Such an error is also pre-send (`isPreSendError`), but the input is what has to change.\n * - `transient`: a read or connection failed with no state change. Repeating the same call is safe\n * and may succeed.\n *\n * This module has no imports: the failure view (`FailureView.outcome`) and the classifier both\n * read the closed set from here.\n */\nexport const FAILURE_OUTCOMES = [\n 'rejected',\n 'unknown',\n 'not_queued',\n 'not_sent',\n 'invalid_input',\n 'transient',\n] as const;\n\n/** One member of {@link FAILURE_OUTCOMES}. */\nexport type FailureOutcome = (typeof FAILURE_OUTCOMES)[number];\n"],"mappings":"AAuBA,MAAaA,EAAmB,CAC9B,WACA,UACA,aACA,WACA,gBACA,WACF,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"failure_view.js","names":["isRecord","value","toFailureView","code","params","status","GALA_ERROR_PHASES","known","phase","uniqueKey","write","FAILURE_OUTCOMES","outcome","retryable","shadow","notFound","isWriteView","view","stringParamOf","name","numberParamOf"],"sources":["../../../src/utils/failure_view.ts"],"sourcesContent":["import { GALA_ERROR_PHASES, type GalaErrorPhase } from '../classes/error_phases.js';\nimport { FAILURE_OUTCOMES, type FailureOutcome } from './failure_outcomes.js';\n\n/**\n * A failure as a PLAIN OBJECT: the facts the SDKs' guards and classifiers (gswap-sdk's\n * `classifyFailure`) read, and nothing else. A real `GalaSDKError` is one (every field below is on\n * it, and on every product subclass); so is the wrapper an app makes from an SDK error to carry\n * through its own layers (an app's own failure class or error data), which\n * has a `code` and `params` but is not an `instanceof` anything the SDK owns. gswap-sdk's\n * `classifyFailure`, `isRelayableRefusal`, `isUnprovenAcknowledgement`, `isUninterpretedAnswer`,\n * `isPreSendError`, `isShadowError`, `isNoMarket` and `mayHaveBeenQueued` all accept such an\n * object wherever they accept an SDK error, and decide from the SAME fields in the same way, so an\n * app never has to keep the original error just to ask.\n *\n * Only `code` is required. A field that is missing, or has the wrong type, reads as absent: a view\n * with no `status` is not a 404. Nothing here is text: the SDK never reads `message` of a view.\n *\n * READ OR WRITE: a view is a WRITE's unless it says it is a read. This fails CLOSED on purpose:\n * a 5xx on a write may have been queued (`unknown`, no retry) and the same 5xx on a read changed\n * nothing (`transient`, retry), so a wrapper that drops its `uniqueKey` must never turn the first\n * into the second. A view is a read ONLY when it states `write: false` and has no `uniqueKey`;\n * `GalaSDKError.write` is already set that way for every SDK read. {@link isWriteView}\n * is the one definition.\n *\n * APP ERRORS: a code the SDK catalog does not define is `unknown` (the SDK cannot say what\n * happened, and a wrong \"failed\" invites a duplicate), unless the view declares `outcome`.\n */\nexport interface FailureView {\n /** The catalog code (`'HTTP_ERROR'`, `'CHAIN_REJECTED'`, ...). A string the SDK does not know classifies as `unknown`. */\n readonly code: string;\n /** The error's flat params (`status` of an `HTTP_ERROR`, `reason` of a `SIGNING_FAILED`, ...). */\n readonly params?: Readonly<Record<string, unknown>> | undefined;\n /** The HTTP status of the answer the failure was made from. */\n readonly status?: number | undefined;\n /** How far the request got; when absent, the catalog's phase for `code`. */\n readonly phase?: GalaErrorPhase | undefined;\n /** The `uniqueKey` of the WRITE this is about; its presence makes the failure a write's. */\n readonly uniqueKey?: string | undefined;\n /**\n * `false` says the failed call was a READ (no `uniqueKey` to confirm, nothing pending). Anything\n * else, including absent, is a write: see the note on {@link FailureView}. With a `uniqueKey`\n * the failure is a write whatever this says.\n */\n readonly write?: boolean | undefined;\n /**\n * What an error the APP raised means, for a `code` the SDK catalog does not define (`'POSITION_STALE'`,\n * `'AMOUNT_SIDE'`): `not_sent` for a step that failed before anything was signed or sent, and so\n * on. The SDK honours it ONLY for such a code: for a catalog code the SDK's own table decides, so\n * an app cannot declare a refusal the SDK knows to be unknown as safe. A non-catalog code with no\n * `outcome` stays `unknown`, and `mayHaveBeenQueued` is then `true`.\n */\n readonly outcome?: FailureOutcome | undefined;\n /**\n * WITHHOLD-ONLY: `false` takes Retry away from the declared `outcome` (an app's `DID_NOT_QUEUE`\n * is `{ outcome: 'not_queued', retryable: false }`, the SDK's `NOT_QUEUED_FINAL`). Any other\n * value, `true` included, reads as absent: a view can never GRANT Retry to an outcome that does\n * not have it, and it is read only together with `outcome`, for a code the catalog does not\n * define.\n */\n readonly retryable?: false | undefined;\n /** True when the failure came from the shadow (dark) path. */\n readonly shadow?: boolean | undefined;\n /** True for \"that thing does not exist\" (`GalaSDKError.notFound`: a market, for gswap-sdk). */\n readonly notFound?: boolean | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Reads the failure view of any value: a `GalaSDKError`, or a plain object with a string `code`\n * (and, optionally, `params`, `status`, `phase`, `uniqueKey`, `shadow`, `notFound`). Anything else\n * (a string, a wallet error with a numeric `code`, `null`) has no view and is `undefined`.\n *\n * Having a view does not mean the SDK knows the code: an ethers error is `{ code:\n * 'ACTION_REJECTED' }` and has a view too. The SDK's guards compare the code with the catalog.\n *\n * @example\n * ```ts\n * const view = toFailureView(error); // an SDK error, or an app's `{ code, params, status }` wrapper\n * if (view?.code === 'CHAIN_REJECTED') showChainRejection(view.params);\n * ```\n */\nexport function toFailureView(value: unknown): FailureView | undefined {\n if (!isRecord(value)) return undefined;\n const { code, params, status, phase, uniqueKey, write, outcome, retryable, shadow, notFound } =\n value;\n if (typeof code !== 'string' || code === '') return undefined;\n return {\n code,\n params: isRecord(params) && !Array.isArray(params) ? params : undefined,\n status: typeof status === 'number' && Number.isFinite(status) ? status : undefined,\n phase: GALA_ERROR_PHASES.find((known) => known === phase),\n uniqueKey: typeof uniqueKey === 'string' && uniqueKey !== '' ? uniqueKey : undefined,\n write: typeof write === 'boolean' ? write : undefined,\n outcome: FAILURE_OUTCOMES.find((known) => known === outcome),\n retryable: retryable === false ? false : undefined,\n shadow: typeof shadow === 'boolean' ? shadow : undefined,\n notFound: typeof notFound === 'boolean' ? notFound : undefined,\n };\n}\n\n/**\n * True when a failure is a WRITE's: it names a `uniqueKey`, or it does not say `write: false`.\n * Fail-closed (see {@link FailureView}): only an explicit read is a read.\n */\nexport function isWriteView(view: FailureView): boolean {\n return view.uniqueKey !== undefined || view.write !== false;\n}\n\n/** A param of a view, when it is a string. */\nexport function stringParamOf(view: FailureView, name: string): string | undefined {\n const value = view.params?.[name];\n return typeof value === 'string' ? value : undefined;\n}\n\n/** A param of a view, when it is a finite number. */\nexport function numberParamOf(view: FailureView, name: string): number | undefined {\n const value = view.params?.[name];\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n"],"mappings":"wHAkEA,SAASA,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAgBA,SAAgBC,EAAc,EAAyC,CACrE,GAAI,CAACF,EAASC,CAAK,EAAG,OACtB,GAAM,CAAE,OAAM,SAAQ,SAAQ,QAAO,YAAW,QAAO,UAAS,YAAW,SAAQ,YACjFA,EACF,GAAI,OAAOE,GAAS,UAAYA,IAAS,GACzC,MAAO,CACL,OACA,OAAQH,EAASI,CAAM,GAAK,CAAC,MAAM,QAAQA,CAAM,EAAIA,EAAS,IAAA,GAC9D,OAAQ,OAAOC,GAAW,UAAY,OAAO,SAASA,CAAM,EAAIA,EAAS,IAAA,GACzE,MAAOC,EAAkB,KAAM,GAAUC,IAAUC,CAAK,EACxD,UAAW,OAAOC,GAAc,UAAYA,IAAc,GAAKA,EAAY,IAAA,GAC3E,MAAO,OAAOC,GAAU,UAAYA,EAAQ,IAAA,GAC5C,QAASC,EAAiB,KAAM,GAAUJ,IAAUK,CAAO,EAC3D,UAAWC,IAAc,IAAgB,IAAA,GACzC,OAAQ,OAAOC,GAAW,UAAYA,EAAS,IAAA,GAC/C,SAAU,OAAOC,GAAa,UAAYA,EAAW,IAAA,EACvD,CACF,CAMA,SAAgBC,EAAY,EAA4B,CACtD,OAAOC,EAAK,YAAc,IAAA,IAAaA,EAAK,QAAU,EACxD,CAGA,SAAgBC,EAAc,EAAmB,EAAkC,CACjF,IAAMjB,EAAQgB,EAAK,SAASE,GAC5B,OAAO,OAAOlB,GAAU,SAAWA,EAAQ,IAAA,EAC7C,CAGA,SAAgBmB,EAAc,EAAmB,EAAkC,CACjF,IAAMnB,EAAQgB,EAAK,SAASE,GAC5B,OAAO,OAAOlB,GAAU,UAAY,OAAO,SAASA,CAAK,EAAIA,EAAQ,IAAA,EACvE"}
1
+ {"version":3,"file":"failure_view.js","names":["isRecord","value","toFailureView","code","params","status","GALA_ERROR_PHASES","known","phase","uniqueKey","write","FAILURE_OUTCOMES","outcome","retryable","shadow","notFound","isWriteView","view","stringParamOf","name","numberParamOf"],"sources":["../../../src/utils/failure_view.ts"],"sourcesContent":["import { GALA_ERROR_PHASES, type GalaErrorPhase } from '../classes/error_phases.js';\nimport { FAILURE_OUTCOMES, type FailureOutcome } from './failure_outcomes.js';\n\n/**\n * A failure as a PLAIN OBJECT: the facts the SDKs' guards and classifiers (gswap-sdk's\n * `classifyFailure`) read, and nothing else. A real `GalaSDKError` is one (every field below is on\n * it, and on every product subclass); so is the wrapper an app makes from an SDK error to carry\n * through its own layers (an app's own failure class or error data), which\n * has a `code` and `params` but is not an `instanceof` anything the SDK owns. gswap-sdk's\n * `classifyFailure`, `isRelayableRefusal`, `isUnprovenAcknowledgement`, `isUninterpretedAnswer`,\n * `isPreSendError`, `isShadowError`, `isNoMarket` and `mayHaveBeenQueued` all accept such an\n * object wherever they accept an SDK error, and decide from the SAME fields in the same way, so an\n * app never has to keep the original error just to ask.\n *\n * Only `code` is required. A field that is missing, or has the wrong type, reads as absent: a view\n * with no `status` is not a 404. Nothing here is text: the SDK never reads `message` of a view.\n *\n * READ OR WRITE: a view is a WRITE's unless it says it is a read. This fails CLOSED on purpose:\n * a 5xx on a write may have been queued (`unknown`, no retry) and the same 5xx on a read changed\n * nothing (`transient`, retry), so a wrapper that drops its `uniqueKey` must never turn the first\n * into the second. A view is a read ONLY when it states `write: false` and has no `uniqueKey`;\n * `GalaSDKError.write` is already set that way for every SDK read. {@link isWriteView}\n * is the one definition.\n *\n * APP ERRORS: a code the SDK catalog does not define is `unknown` (the SDK cannot say what\n * happened, and a wrong \"failed\" invites a duplicate), unless the view declares `outcome`.\n */\nexport interface FailureView {\n /** The catalog code (`'HTTP_ERROR'`, `'CHAIN_REJECTED'`, ...). A string the SDK does not know classifies as `unknown`. */\n readonly code: string;\n /** The error's flat params (`status` of an `HTTP_ERROR`, `reason` of a `SIGNING_FAILED`, ...). */\n readonly params?: Readonly<Record<string, unknown>> | undefined;\n /** The HTTP status of the answer the failure was made from. */\n readonly status?: number | undefined;\n /** How far the request got; when absent, the catalog's phase for `code`. */\n readonly phase?: GalaErrorPhase | undefined;\n /** The `uniqueKey` of the WRITE this is about; its presence makes the failure a write's. */\n readonly uniqueKey?: string | undefined;\n /**\n * `false` says the failed call was a READ (no `uniqueKey` to confirm, nothing pending). Anything\n * else, including absent, is a write: see the note on {@link FailureView}. With a `uniqueKey`\n * the failure is a write whatever this says.\n */\n readonly write?: boolean | undefined;\n /**\n * What an error the APP raised means, for a `code` the SDK catalog does not define (`'POSITION_STALE'`,\n * `'AMOUNT_SIDE'`): `not_sent` for a step that failed before anything was signed or sent, and so\n * on. The SDK honours it ONLY for such a code: for a catalog code the SDK's own table decides, so\n * an app cannot declare a refusal the SDK knows to be unknown as safe. A non-catalog code with no\n * `outcome` stays `unknown`, and `mayHaveBeenQueued` is then `true`.\n */\n readonly outcome?: FailureOutcome | undefined;\n /**\n * WITHHOLD-ONLY: `false` takes Retry away from the declared `outcome` (an app's `DID_NOT_QUEUE`\n * is `{ outcome: 'not_queued', retryable: false }`, the SDK's `NOT_QUEUED_FINAL`). Any other\n * value, `true` included, reads as absent: a view can never GRANT Retry to an outcome that does\n * not have it, and it is read only together with `outcome`, for a code the catalog does not\n * define.\n */\n readonly retryable?: false | undefined;\n /** True when the failure came from the shadow (dark) path. */\n readonly shadow?: boolean | undefined;\n /** True for \"that thing does not exist\" (`GalaSDKError.notFound`: a market, for gswap-sdk). */\n readonly notFound?: boolean | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Reads the failure view of any value: a `GalaSDKError`, or a plain object with a string `code`\n * (and, optionally, `params`, `status`, `phase`, `uniqueKey`, `shadow`, `notFound`). Anything else\n * (a string, a wallet error with a numeric `code`, `null`) has no view and is `undefined`.\n *\n * Having a view does not mean the SDK knows the code: an ethers error is `{ code:\n * 'ACTION_REJECTED' }` and has a view too. The SDK's guards compare the code with the catalog.\n *\n * @example\n * ```ts\n * const view = toFailureView(error); // an SDK error, or an app's `{ code, params, status }` wrapper\n * if (view?.code === 'CHAIN_REJECTED') showChainRejection(view.params);\n * ```\n */\nexport function toFailureView(value: unknown): FailureView | undefined {\n if (!isRecord(value)) return undefined;\n const { code, params, status, phase, uniqueKey, write, outcome, retryable, shadow, notFound } =\n value;\n if (typeof code !== 'string' || code === '') return undefined;\n return {\n code,\n params: isRecord(params) && !Array.isArray(params) ? params : undefined,\n status: typeof status === 'number' && Number.isFinite(status) ? status : undefined,\n phase: GALA_ERROR_PHASES.find((known) => known === phase),\n uniqueKey: typeof uniqueKey === 'string' && uniqueKey !== '' ? uniqueKey : undefined,\n write: typeof write === 'boolean' ? write : undefined,\n outcome: FAILURE_OUTCOMES.find((known) => known === outcome),\n retryable: retryable === false ? false : undefined,\n shadow: typeof shadow === 'boolean' ? shadow : undefined,\n notFound: typeof notFound === 'boolean' ? notFound : undefined,\n };\n}\n\n/**\n * True when a failure is a WRITE's: it names a `uniqueKey`, or it does not say `write: false`.\n * Fail-closed (see {@link FailureView}): only an explicit read is a read.\n */\nexport function isWriteView(view: FailureView): boolean {\n return view.uniqueKey !== undefined || view.write !== false;\n}\n\n/** A param of a view, when it is a string. */\nexport function stringParamOf(view: FailureView, name: string): string | undefined {\n const value = view.params?.[name];\n return typeof value === 'string' ? value : undefined;\n}\n\n/** A param of a view, when it is a finite number. */\nexport function numberParamOf(view: FailureView, name: string): number | undefined {\n const value = view.params?.[name];\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n"],"mappings":"A,wHAkEA,SAASA,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAgBA,SAAgBC,EAAc,EAAyC,CACrE,GAAI,CAACF,EAASC,CAAK,EAAG,OACtB,GAAM,CAAE,OAAM,SAAQ,SAAQ,QAAO,YAAW,QAAO,UAAS,YAAW,SAAQ,YACjFA,EACF,GAAI,OAAOE,GAAS,UAAYA,IAAS,GACzC,MAAO,CACL,OACA,OAAQH,EAASI,CAAM,GAAK,CAAC,MAAM,QAAQA,CAAM,EAAIA,EAAS,IAAA,GAC9D,OAAQ,OAAOC,GAAW,UAAY,OAAO,SAASA,CAAM,EAAIA,EAAS,IAAA,GACzE,MAAOC,EAAkB,KAAM,GAAUC,IAAUC,CAAK,EACxD,UAAW,OAAOC,GAAc,UAAYA,IAAc,GAAKA,EAAY,IAAA,GAC3E,MAAO,OAAOC,GAAU,UAAYA,EAAQ,IAAA,GAC5C,QAASC,EAAiB,KAAM,GAAUJ,IAAUK,CAAO,EAC3D,UAAWC,IAAc,IAAgB,IAAA,GACzC,OAAQ,OAAOC,GAAW,UAAYA,EAAS,IAAA,GAC/C,SAAU,OAAOC,GAAa,UAAYA,EAAW,IAAA,EACvD,CACF,CAMA,SAAgBC,EAAY,EAA4B,CACtD,OAAOC,EAAK,YAAc,IAAA,IAAaA,EAAK,QAAU,EACxD,CAGA,SAAgBC,EAAc,EAAmB,EAAkC,CACjF,IAAMjB,EAAQgB,EAAK,SAASE,GAC5B,OAAO,OAAOlB,GAAU,SAAWA,EAAQ,IAAA,EAC7C,CAGA,SAAgBmB,EAAc,EAAmB,EAAkC,CACjF,IAAMnB,EAAQgB,EAAK,SAASE,GAC5B,OAAO,OAAOlB,GAAU,UAAY,OAAO,SAASA,CAAK,EAAIA,EAAQ,IAAA,EACvE,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch_failure.js","names":["isFetchTransportFailure","error","name"],"sources":["../../../src/utils/fetch_failure.ts"],"sourcesContent":["/**\n * True when a rejection of a `fetch`-based requestor means NO HTTP ANSWER ARRIVED: the network\n * failed, the connection was reset, the host did not resolve, CORS blocked it. For a write that\n * is not a refusal (the request may have been queued), so this is the default\n * `ChainGatewayOptions.isTransportFailure` for a requestor that wraps `fetch` and rejects with\n * its own errors.\n *\n * - Yes: a `TypeError` (what `fetch` rejects with in every engine: `Failed to fetch`, `Load failed`,\n * `NetworkError when attempting to fetch resource`, undici's `fetch failed`), recognised by name\n * too so one from another realm (an extension page, an iframe) still counts, and a\n * `DOMException` named `NetworkError`.\n * - No: an abort (`AbortError`) or a timeout (`TimeoutError`). The SDK's own request layer knows\n * whether its timer or the caller's signal aborted, and reports those itself\n * (`REQUEST_TIMEOUT`, or the caller's own abort unchanged); claiming them here would turn the\n * caller's cancel into \"maybe queued\".\n * - No: anything else, including an SDK error and a value that is not an object.\n *\n * It never throws.\n *\n * @example\n * ```ts\n * new ChainGateway({ dexBackendBaseUrl, httpRequestor: galaFetch, isTransportFailure: isFetchTransportFailure });\n * ```\n */\nexport function isFetchTransportFailure(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n try {\n const name: unknown = 'name' in error ? error.name : undefined;\n if (name === 'AbortError' || name === 'TimeoutError') return false;\n return error instanceof TypeError || name === 'TypeError' || name === 'NetworkError';\n } catch {\n // A hostile or revoked object (a Proxy that throws on property access) proves nothing.\n return false;\n }\n}\n"],"mappings":"AAwBA,SAAgBA,EAAwB,EAAyB,CAC/D,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,GAAI,CACF,IAAMC,EAAgB,SAAUD,EAAQA,EAAM,KAAO,IAAA,GAErD,OADIC,IAAS,cAAgBA,IAAS,eAAuB,GACtDD,aAAiB,WAAaC,IAAS,aAAeA,IAAS,cACxE,MAAQ,CAEN,MAAO,EACT,CACF"}
1
+ {"version":3,"file":"fetch_failure.js","names":["isFetchTransportFailure","error","name"],"sources":["../../../src/utils/fetch_failure.ts"],"sourcesContent":["/**\n * True when a rejection of a `fetch`-based requestor means NO HTTP ANSWER ARRIVED: the network\n * failed, the connection was reset, the host did not resolve, CORS blocked it. For a write that\n * is not a refusal (the request may have been queued), so this is the default\n * `ChainGatewayOptions.isTransportFailure` for a requestor that wraps `fetch` and rejects with\n * its own errors.\n *\n * - Yes: a `TypeError` (what `fetch` rejects with in every engine: `Failed to fetch`, `Load failed`,\n * `NetworkError when attempting to fetch resource`, undici's `fetch failed`), recognised by name\n * too so one from another realm (an extension page, an iframe) still counts, and a\n * `DOMException` named `NetworkError`.\n * - No: an abort (`AbortError`) or a timeout (`TimeoutError`). The SDK's own request layer knows\n * whether its timer or the caller's signal aborted, and reports those itself\n * (`REQUEST_TIMEOUT`, or the caller's own abort unchanged); claiming them here would turn the\n * caller's cancel into \"maybe queued\".\n * - No: anything else, including an SDK error and a value that is not an object.\n *\n * It never throws.\n *\n * @example\n * ```ts\n * new ChainGateway({ dexBackendBaseUrl, httpRequestor: galaFetch, isTransportFailure: isFetchTransportFailure });\n * ```\n */\nexport function isFetchTransportFailure(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n try {\n const name: unknown = 'name' in error ? error.name : undefined;\n if (name === 'AbortError' || name === 'TimeoutError') return false;\n return error instanceof TypeError || name === 'TypeError' || name === 'NetworkError';\n } catch {\n // A hostile or revoked object (a Proxy that throws on property access) proves nothing.\n return false;\n }\n}\n"],"mappings":"AAwBA,SAAgBA,EAAwB,EAAyB,CAC/D,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,GAAI,CACF,IAAMC,EAAgB,SAAUD,EAAQA,EAAM,KAAO,IAAA,GAErD,OADIC,IAAS,cAAgBA,IAAS,eAAuB,GACtDD,aAAiB,WAAaC,IAAS,aAAeA,IAAS,cACxE,MAAQ,CAEN,MAAO,EACT,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{GalaSDKError as e,isGalaError as t}from"../classes/gala_sdk_error.js";import{isWalletUserRejection as n,walletDeclineCode as r}from"./wallet_rejection.js";async function i(i,a,o){let s;try{s=await i.signObject(a,o)}catch(i){if(t(i))throw i;let o=n(i)?`user_rejected`:`failed`;throw new e(`SIGNING_FAILED`,{method:a,reason:o},{cause:i,walletCode:r(i)})}if(typeof s!=`object`||!s)throw new e(`SIGNING_FAILED`,{method:a,reason:`failed`},{cause:s});return s}export{i as signPreSend};
1
+ import{GalaSDKError as e,isGalaError as t}from"../classes/gala_sdk_error.js";import{withDtoOperation as n}from"./dto_operation.js";import{isWalletUserRejection as r,walletDeclineCode as i}from"./wallet_rejection.js";async function a(a,o,s,c){let l;try{l=await a.signObject(s,n(o,s,c))}catch(n){if(t(n))throw n;let a=r(n)?`user_rejected`:`failed`;throw new e(`SIGNING_FAILED`,{method:s,reason:a},{cause:n,walletCode:i(n)})}if(typeof l!=`object`||!l)throw new e(`SIGNING_FAILED`,{method:s,reason:`failed`},{cause:l});return l}export{a as signPreSend};
2
2
  //# sourceMappingURL=pre_send.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pre_send.js","names":["signPreSend","signed","signer","method","dto","cause","isGalaError","reason","isWalletUserRejection","GalaSDKError","walletDeclineCode"],"sources":["../../../src/utils/pre_send.ts"],"sourcesContent":["import { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport type { GalaChainSigner, SignedDto } from '../classes/signers.js';\nimport { isWalletUserRejection, walletDeclineCode } from './wallet_rejection.js';\n\n/**\n * The boundary of \"nothing was sent\". Every place where an SDK hands control to code the APP\n * supplied BEFORE the request leaves (the signer here; a product SDK's token resolver) goes through\n * such a wrapper, so a failure of that code reaches the caller as a catalogued, pre-send SDK error\n * with the original as `cause`, never as a bare value the SDK cannot classify. An SDK error thrown\n * by that code is already catalogued and passes through untouched. Nothing here is used after the\n * request has been sent: an app's own rejection AFTER send stays what it is, because the SDK\n * cannot know what the server did with the write.\n */\n\n/**\n * Signs a DTO with the app's signer. Whatever the signer throws that is not already an SDK error\n * (a locked wallet, an unreachable extension, a wallet that declined) is `SIGNING_FAILED`\n * (`reason` `user_rejected` or `failed`, the original as `cause`), and a signer that returns\n * something other than an object is `SIGNING_FAILED` too: both are pre-send, so a retry is safe.\n * An SDK error of ANY product (every one is a `GalaSDKError`) passes through as it is.\n *\n * @throws GalaSDKError SIGNING_FAILED, or the SDK error the signer itself threw.\n */\nexport async function signPreSend<T extends Record<string, unknown>>(\n signer: GalaChainSigner,\n method: string,\n dto: T,\n): Promise<SignedDto<T>> {\n let signed: SignedDto<T>;\n try {\n signed = await signer.signObject(method, dto);\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n const reason = isWalletUserRejection(cause) ? 'user_rejected' : 'failed';\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n { method, reason },\n { cause, walletCode: walletDeclineCode(cause) },\n );\n }\n if (typeof signed !== 'object' || signed === null) {\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause: signed });\n }\n return signed;\n}\n"],"mappings":"kKAuBA,eAAsBA,EACpB,EACA,EACA,EACuB,CACvB,IAAIC,EACJ,GAAI,CACF,EAAS,MAAMC,EAAO,WAAWC,EAAQC,CAAG,CAC9C,OAASC,EAAgB,CACvB,GAAIC,EAAYD,CAAK,EAAG,MAAMA,EAC9B,IAAME,EAASC,EAAsBH,CAAK,EAAI,gBAAkB,SAChE,MAAM,IAAII,EACR,iBACA,CAAE,SAAQ,QAAO,EACjB,CAAE,QAAO,WAAYC,EAAkBL,CAAK,CAAE,CAChD,CACF,CACA,GAAI,OAAOJ,GAAW,WAAYA,EAChC,MAAM,IAAIQ,EAAa,iBAAkB,CAAE,SAAQ,OAAQ,QAAS,EAAG,CAAE,MAAOR,CAAO,CAAC,EAE1F,OAAOA,CACT"}
1
+ {"version":3,"file":"pre_send.js","names":["signPreSend","signed","signer","method","withDtoOperation","contractPath","dto","cause","isGalaError","reason","isWalletUserRejection","GalaSDKError","walletDeclineCode"],"sources":["../../../src/utils/pre_send.ts"],"sourcesContent":["import { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport type { GalaChainSigner, SignedDto } from '../classes/signers.js';\nimport { withDtoOperation, type ChainContractPath } from './dto_operation.js';\nimport { isWalletUserRejection, walletDeclineCode } from './wallet_rejection.js';\n\n/**\n * The boundary of \"nothing was sent\". Every place where an SDK hands control to code the APP\n * supplied BEFORE the request leaves (the signer here; a product SDK's token resolver) goes through\n * such a wrapper, so a failure of that code reaches the caller as a catalogued, pre-send SDK error\n * with the original as `cause`, never as a bare value the SDK cannot classify. An SDK error thrown\n * by that code is already catalogued and passes through untouched. Nothing here is used after the\n * request has been sent: an app's own rejection AFTER send stays what it is, because the SDK\n * cannot know what the server did with the write.\n */\n\n/**\n * Signs a DTO with the app's signer, after setting its `dtoOperation` to the operation of `method`\n * on the contract at `contractPath` (the chain refuses a DTO signed for another operation). Whatever the signer throws that is not already an SDK error\n * (a locked wallet, an unreachable extension, a wallet that declined) is `SIGNING_FAILED`\n * (`reason` `user_rejected` or `failed`, the original as `cause`), and a signer that returns\n * something other than an object is `SIGNING_FAILED` too: both are pre-send, so a retry is safe.\n * An SDK error of ANY product (every one is a `GalaSDKError`) passes through as it is.\n *\n * @throws GalaSDKError SIGNING_FAILED, or the SDK error the signer itself threw.\n */\nexport async function signPreSend<T extends Record<string, unknown>>(\n signer: GalaChainSigner,\n contractPath: ChainContractPath,\n method: string,\n dto: T,\n): Promise<SignedDto<T>> {\n let signed: SignedDto<T>;\n try {\n signed = await signer.signObject(method, withDtoOperation(contractPath, method, dto));\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n const reason = isWalletUserRejection(cause) ? 'user_rejected' : 'failed';\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n { method, reason },\n { cause, walletCode: walletDeclineCode(cause) },\n );\n }\n if (typeof signed !== 'object' || signed === null) {\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause: signed });\n }\n return signed;\n}\n"],"mappings":"A,wNAyBA,eAAsBA,EACpB,EACA,EACA,EACA,EACuB,CACvB,IAAIC,EACJ,GAAI,CACF,EAAS,MAAMC,EAAO,WAAWC,EAAQC,EAAiBC,EAAcF,EAAQG,CAAG,CAAC,CACtF,OAASC,EAAgB,CACvB,GAAIC,EAAYD,CAAK,EAAG,MAAMA,EAC9B,IAAME,EAASC,EAAsBH,CAAK,EAAI,gBAAkB,SAChE,MAAM,IAAII,EACR,iBACA,CAAE,SAAQ,QAAO,EACjB,CAAE,QAAO,WAAYC,EAAkBL,CAAK,CAAE,CAChD,CACF,CACA,GAAI,OAAON,GAAW,WAAYA,EAChC,MAAM,IAAIU,EAAa,iBAAkB,CAAE,SAAQ,OAAQ,QAAS,EAAG,CAAE,MAAOV,CAAO,CAAC,EAE1F,OAAOA,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"signing.js","names":["textEncoder","toDeterministicNode","node","candidate","deterministicNode","rawNode","item","record","members","key","value","serialize","result","getPayloadToSign","rest","dto","\"signature\"","\"multisig\"","\"trace\"","prefix","ETHEREUM_SIGNED_MESSAGE","calculatePersonalSignPrefix","message","personalSignPrefixFor","withoutPrefix","\"prefix\"","fixpointPrefixFor","payloadLength","previousLength","invalidPrivateKey","GalaSDKError","decodeBase64","input","unpadded","bytes","buffer","bits","char","decodeHex","index","normalizePrivateKey","secp256k1","signHash","hash","signature","privateKey","bytesToHex","ethAddressOfPrivateKey","publicKey","keccak_256","keccak256Utf8","data","signSerializedNative","serializedDto","signNative","signPersonalMessage"],"sources":["../../../src/utils/signing.ts"],"sourcesContent":["/**\n * SDK-owned signing primitives.\n *\n * Everything the SDK needs to produce a GalaChain signature lives here, with no dependency on\n * `@gala-chain/api` (which drags `secp256k1` native bindings, `reflect-metadata`, `class-validator`\n * and its own `bignumber.js` major into every consumer). The only runtime dependencies are the\n * audited, pure-JS `@noble/curves` (secp256k1) and `@noble/hashes` (keccak256), which run\n * unchanged in browsers, MV3 service workers, Node and React Native/Hermes.\n *\n * Every function here is pinned byte-for-byte to the signatures produced by `@gala-chain/api`\n * (`serialize`, `signatures.getSignature`), `@gala-chain/connect`, the Gala Wallet extension and\n * the gSwap web app by the golden-vector suite in `tests/signing-golden.test.ts`.\n */\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\nimport type { InvalidPrivateKeyReason } from '../classes/error_catalog.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\n\nconst textEncoder = new TextEncoder();\n\nfunction toDeterministicNode(node: unknown): unknown {\n if (node === null || node === undefined) return node;\n if (node instanceof RegExp) return node.toString();\n const candidate = node as { toJSON?: unknown };\n return typeof candidate.toJSON === 'function'\n ? (Reflect.apply(candidate.toJSON, node, []) as unknown)\n : node;\n}\n\nfunction deterministicNode(rawNode: unknown): string | undefined {\n const node = toDeterministicNode(rawNode);\n if (node === undefined) return undefined;\n if (typeof node !== 'object' || node === null) return JSON.stringify(node);\n\n if (Array.isArray(node)) {\n const items = (node as unknown[]).map((item) => deterministicNode(item) ?? 'null');\n return `[${items.join(',')}]`;\n }\n\n const record = node as Record<string, unknown>;\n const members: string[] = [];\n for (const key of Object.keys(record).sort()) {\n const value = deterministicNode(record[key]);\n if (value === undefined) continue;\n members.push(`${JSON.stringify(key)}:${value}`);\n }\n return `{${members.join(',')}}`;\n}\n\n/**\n * GalaChain's deterministic JSON: object keys sorted (UTF-16 code-unit order) at every depth, no\n * whitespace, `undefined`/function members dropped, `toJSON()` honored. Byte-identical to\n * `serialize` from `@gala-chain/api` / `json-stringify-deterministic` for every JSON-shaped\n * value, which is all a DTO ever is.\n *\n * @throws TypeError for circular structures and BigInt values (as `JSON.stringify` does) and\n * when the value itself has no JSON representation (`undefined`, a function, a symbol).\n */\nexport function serialize(value: unknown): string {\n // Same cycle/BigInt guard json-stringify-deterministic runs before walking the value.\n JSON.stringify(value);\n const result = deterministicNode(value);\n if (result === undefined) {\n throw new TypeError('Cannot serialize a value with no JSON representation.');\n }\n return result;\n}\n\n/**\n * The exact string GalaChain hashes for a DTO: the (optional, string) `prefix` field PREPENDED to\n * the deterministic serialization of the DTO WITHOUT `signature`, `multisig`, `trace` and `prefix`.\n * Equivalent to `@gala-chain/api` 3.x `getPayloadToSign` for every non-EIP-712 DTO.\n */\nexport function getPayloadToSign(dto: Record<string, unknown>): string {\n const { prefix, ...rest } = dto;\n delete rest['signature'];\n delete rest['multisig'];\n delete rest['trace'];\n const head = typeof prefix === 'string' ? prefix : '';\n return head + serialize(rest);\n}\n\n// Built via String.fromCharCode rather than a literal escape ON PURPOSE: a literal control byte in\n// source is invisible and fragile under editors/diffs/copy-paste; this keeps the source ordinary.\nconst ETHEREUM_SIGNED_MESSAGE = String.fromCharCode(0x19) + 'Ethereum Signed Message:\\n';\n\n/**\n * The EIP-191 header for `message`: `\"\\x19Ethereum Signed Message:\\n\"` + the message's UTF-8 BYTE\n * length. This is what a wallet's `personal_sign` prepends, and what the chain recomputes when it\n * recovers a personal-signed DTO.\n */\nexport function calculatePersonalSignPrefix(message: string): string {\n return ETHEREUM_SIGNED_MESSAGE + String(textEncoder.encode(message).length);\n}\n\n/**\n * The EIP-191 header for `serialize(dto)` (any `prefix` already on the DTO is ignored). This is\n * deliberately the same string the signers hand a wallet to sign, so the header's length can never\n * disagree with the signed message. Wallet-neutral: it is the value both a browser wallet's\n * `personal_sign` and Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepend.\n */\nexport function personalSignPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n return calculatePersonalSignPrefix(serialize(withoutPrefix));\n}\n\n/**\n * The `@gala-chain/connect`-style prefix the gSwap web app puts in the body of an EIP-712 write: the\n * EIP-191 header whose number counts the prefix string ITSELF plus the body (the UTF-8 length of\n * `getPayloadToSign({ ...dto, prefix })`), found by fixpoint because adding the prefix changes the\n * length (a body of 99 bytes settles on 101).\n *\n * It is NOT a personal-sign prefix (a personal-sign write with this value recovers a phantom\n * signer; use `personalSignPrefixFor`). Under EIP-712 the field is an untyped extra that the\n * typed-data hash ignores and the backend recomputes, so it only exists to keep the submitted\n * body byte-identical to what the gSwap web app has always sent.\n */\nexport function fixpointPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n let payloadLength = textEncoder.encode(getPayloadToSign(withoutPrefix)).length;\n let prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n let previousLength = -1;\n while (payloadLength !== previousLength) {\n previousLength = payloadLength;\n prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n payloadLength = textEncoder.encode(getPayloadToSign({ ...withoutPrefix, prefix })).length;\n }\n return prefix;\n}\n\nfunction invalidPrivateKey(reason: InvalidPrivateKeyReason): GalaSDKError<'INVALID_PRIVATE_KEY'> {\n return new GalaSDKError('INVALID_PRIVATE_KEY', { reason });\n}\n\nconst BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nfunction decodeBase64(input: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(input) || input.length % 4 !== 0) return undefined;\n const unpadded = input.replace(/=+$/u, '');\n const bytes: number[] = [];\n let buffer = 0;\n let bits = 0;\n for (const char of unpadded) {\n buffer = (buffer << 6) | BASE64_ALPHABET.indexOf(char);\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((buffer >> bits) & 0xff);\n }\n }\n return Uint8Array.from(bytes);\n}\n\nfunction decodeHex(input: string): Uint8Array {\n const bytes = new Uint8Array(input.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = parseInt(input.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Normalizes a secp256k1 private key to a fresh 32-byte array (the caller may zero it). Also\n * accepts 32 raw bytes, which are validated and copied. For strings it accepts what `@gala-chain/api`'s\n * `normalizePrivateKey` accepted for a usable key: 64 hex characters (optionally `0x`-prefixed;\n * a 63-character hex key is left-padded with a zero) or a 44-character base64 string.\n *\n * @throws GalaSDKError (`INVALID_PRIVATE_KEY`; `params.reason` is one of\n * `INVALID_PRIVATE_KEY_REASONS`: `wrong_length` for raw bytes that are not 32 long,\n * `bad_encoding` for any other string shape, `not_on_curve` for an out-of-range scalar).\n */\nexport function normalizePrivateKey(input: string | Uint8Array): Uint8Array {\n if (typeof input !== 'string') {\n // Raw bytes: validated, then COPIED, so zeroing the result never touches the caller's array.\n if (!(input instanceof Uint8Array) || input.length !== 32) {\n throw invalidPrivateKey('wrong_length');\n }\n if (!secp256k1.utils.isValidSecretKey(input)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return Uint8Array.from(input);\n }\n const withoutPrefix = input.startsWith('0x') ? input.slice(2) : input;\n let key: Uint8Array | undefined;\n if (/^[0-9a-fA-F]{63,64}$/u.test(withoutPrefix)) {\n key = decodeHex(withoutPrefix.length === 63 ? `0${withoutPrefix}` : withoutPrefix);\n } else if (withoutPrefix.length === 44) {\n key = decodeBase64(withoutPrefix);\n }\n if (key?.length !== 32) {\n throw invalidPrivateKey('bad_encoding');\n }\n if (!secp256k1.utils.isValidSecretKey(key)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return key;\n}\n\n/**\n * Signs a 32-byte keccak256 hash and returns GalaChain's recoverable signature: 64 hex `r` +\n * 64 hex `s` + `1b`/`1c` (`v`), lowercase, no `0x`. Deterministic (RFC 6979) and low-S, exactly\n * what `@gala-chain/api` and the Gala Wallet produce. A DER signature carries no recovery byte\n * and cannot be used: the chain RECOVERS the signer from the signature.\n */\nexport function signHash(privateKey: Uint8Array, hash: Uint8Array): string {\n if (hash.length !== 32) {\n throw new GalaSDKError('INVALID_SIGNING_HASH_LENGTH', { length: hash.length });\n }\n const signature = secp256k1.sign(hash, privateKey, { prehash: false, lowS: true });\n // compact raw bytes are r (32) || s (32); the recovery id becomes v.\n return bytesToHex(signature.toBytes('compact')) + (signature.recovery === 1 ? '1c' : '1b');\n}\n\n/**\n * The lowercase `0x` Ethereum address (last 20 bytes of keccak256 of the uncompressed public key)\n * of a normalized private key. The Gala `eth|` identity of a key is this address.\n */\nexport function ethAddressOfPrivateKey(privateKey: Uint8Array): string {\n const publicKey = secp256k1.getPublicKey(privateKey, false);\n return `0x${bytesToHex(keccak_256(publicKey.slice(1)).slice(-20))}`;\n}\n\n/** keccak256 of a string's UTF-8 bytes. */\nexport function keccak256Utf8(data: string): Uint8Array {\n return keccak_256(textEncoder.encode(data));\n}\n\n/**\n * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes, with no\n * prefix and no signature envelope. The caller owns serialization, so the bytes shown to a user\n * and the bytes signed can never diverge.\n */\nexport function signSerializedNative(privateKey: Uint8Array, serializedDto: string): string {\n return signHash(privateKey, keccak256Utf8(serializedDto));\n}\n\n/**\n * GalaChain NATIVE signature for a DTO: keccak256 of `getPayloadToSign(dto)`, signed with\n * secp256k1. Byte-identical to `signatures.getSignature` from `@gala-chain/api`.\n */\nexport function signNative(privateKey: Uint8Array, dto: Record<string, unknown>): string {\n return signSerializedNative(privateKey, getPayloadToSign(dto));\n}\n\n/**\n * Personal-sign hash and signature: keccak256(`prefix` + `message`), both hashed VERBATIM with no\n * further EIP-191 wrapping. Passing `prefix = calculatePersonalSignPrefix(message)` reproduces a\n * wallet's `personal_sign` of `message`. Gala Wallet's `gala_signChainDto` (personal-sign\n * scheme) hashes `prefix` + the exact string it is handed, which can differ from the bare message\n * (see the `signatureOverPrefixlessBody` vectors); that quirk is why the two inputs stay separate.\n */\nexport function signPersonalMessage(\n privateKey: Uint8Array,\n prefix: string,\n message: string,\n): string {\n return signHash(privateKey, keccak256Utf8(prefix + message));\n}\n"],"mappings":"iNAmBA,MAAMA,EAAc,IAAI,YAExB,SAASC,EAAoB,EAAwB,CACnD,GAAIC,GAAS,KAA4B,OAAOA,EAChD,GAAIA,aAAgB,OAAQ,OAAOA,EAAK,SAAS,EACjD,IAAMC,EAAYD,EAClB,OAAO,OAAOC,EAAU,QAAW,WAC9B,QAAQ,MAAMA,EAAU,OAAQD,EAAM,CAAC,CAAC,EACzCA,CACN,CAEA,SAASE,EAAkB,EAAsC,CAC/D,IAAMF,EAAOD,EAAoBI,CAAO,EACxC,GAAIH,IAAS,IAA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Node","item","record","members","key","value","serialize","result","getPayloadToSign","rest","dto","\"signature\"","\"multisig\"","\"trace\"","prefix","ETHEREUM_SIGNED_MESSAGE","calculatePersonalSignPrefix","message","personalSignPrefixFor","withoutPrefix","\"prefix\"","fixpointPrefixFor","payloadLength","previousLength","invalidPrivateKey","GalaSDKError","decodeBase64","input","unpadded","bytes","buffer","bits","char","decodeHex","index","normalizePrivateKey","secp256k1","signHash","hash","signature","privateKey","bytesToHex","ethAddressOfPrivateKey","publicKey","keccak_256","keccak256Utf8","data","signSerializedNative","serializedDto","signNative","signPersonalMessage"],"sources":["../../../src/utils/signing.ts"],"sourcesContent":["/**\n * SDK-owned signing primitives.\n *\n * Everything the SDK needs to produce a GalaChain signature lives here, with no dependency on\n * `@gala-chain/api` (which drags `secp256k1` native bindings, `reflect-metadata`, `class-validator`\n * and its own `bignumber.js` major into every consumer). The only runtime dependencies are the\n * audited, pure-JS `@noble/curves` (secp256k1) and `@noble/hashes` (keccak256), which run\n * unchanged in browsers, MV3 service workers, Node and React Native/Hermes.\n *\n * Every function here is pinned byte-for-byte to the signatures produced by `@gala-chain/api`\n * (`serialize`, `signatures.getSignature`), `@gala-chain/connect`, the Gala Wallet extension and\n * the gSwap web app by the golden-vector suite in `tests/signing-golden.test.ts`.\n */\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\nimport type { InvalidPrivateKeyReason } from '../classes/error_catalog.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\n\nconst textEncoder = new TextEncoder();\n\nfunction toDeterministicNode(node: unknown): unknown {\n if (node === null || node === undefined) return node;\n if (node instanceof RegExp) return node.toString();\n const candidate = node as { toJSON?: unknown };\n return typeof candidate.toJSON === 'function'\n ? (Reflect.apply(candidate.toJSON, node, []) as unknown)\n : node;\n}\n\nfunction deterministicNode(rawNode: unknown): string | undefined {\n const node = toDeterministicNode(rawNode);\n if (node === undefined) return undefined;\n if (typeof node !== 'object' || node === null) return JSON.stringify(node);\n\n if (Array.isArray(node)) {\n const items = (node as unknown[]).map((item) => deterministicNode(item) ?? 'null');\n return `[${items.join(',')}]`;\n }\n\n const record = node as Record<string, unknown>;\n const members: string[] = [];\n for (const key of Object.keys(record).sort()) {\n const value = deterministicNode(record[key]);\n if (value === undefined) continue;\n members.push(`${JSON.stringify(key)}:${value}`);\n }\n return `{${members.join(',')}}`;\n}\n\n/**\n * GalaChain's deterministic JSON: object keys sorted (UTF-16 code-unit order) at every depth, no\n * whitespace, `undefined`/function members dropped, `toJSON()` honored. Byte-identical to\n * `serialize` from `@gala-chain/api` / `json-stringify-deterministic` for every JSON-shaped\n * value, which is all a DTO ever is.\n *\n * @throws TypeError for circular structures and BigInt values (as `JSON.stringify` does) and\n * when the value itself has no JSON representation (`undefined`, a function, a symbol).\n */\nexport function serialize(value: unknown): string {\n // Same cycle/BigInt guard json-stringify-deterministic runs before walking the value.\n JSON.stringify(value);\n const result = deterministicNode(value);\n if (result === undefined) {\n throw new TypeError('Cannot serialize a value with no JSON representation.');\n }\n return result;\n}\n\n/**\n * The exact string GalaChain hashes for a DTO: the (optional, string) `prefix` field PREPENDED to\n * the deterministic serialization of the DTO WITHOUT `signature`, `multisig`, `trace` and `prefix`.\n * Equivalent to `@gala-chain/api` 3.x `getPayloadToSign` for every non-EIP-712 DTO.\n */\nexport function getPayloadToSign(dto: Record<string, unknown>): string {\n const { prefix, ...rest } = dto;\n delete rest['signature'];\n delete rest['multisig'];\n delete rest['trace'];\n const head = typeof prefix === 'string' ? prefix : '';\n return head + serialize(rest);\n}\n\n// Built via String.fromCharCode rather than a literal escape ON PURPOSE: a literal control byte in\n// source is invisible and fragile under editors/diffs/copy-paste; this keeps the source ordinary.\nconst ETHEREUM_SIGNED_MESSAGE = String.fromCharCode(0x19) + 'Ethereum Signed Message:\\n';\n\n/**\n * The EIP-191 header for `message`: `\"\\x19Ethereum Signed Message:\\n\"` + the message's UTF-8 BYTE\n * length. This is what a wallet's `personal_sign` prepends, and what the chain recomputes when it\n * recovers a personal-signed DTO.\n */\nexport function calculatePersonalSignPrefix(message: string): string {\n return ETHEREUM_SIGNED_MESSAGE + String(textEncoder.encode(message).length);\n}\n\n/**\n * The EIP-191 header for `serialize(dto)` (any `prefix` already on the DTO is ignored). This is\n * deliberately the same string the signers hand a wallet to sign, so the header's length can never\n * disagree with the signed message. Wallet-neutral: it is the value both a browser wallet's\n * `personal_sign` and Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepend.\n */\nexport function personalSignPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n return calculatePersonalSignPrefix(serialize(withoutPrefix));\n}\n\n/**\n * The `@gala-chain/connect`-style prefix the gSwap web app puts in the body of an EIP-712 write: the\n * EIP-191 header whose number counts the prefix string ITSELF plus the body (the UTF-8 length of\n * `getPayloadToSign({ ...dto, prefix })`), found by fixpoint because adding the prefix changes the\n * length (a body of 99 bytes settles on 101).\n *\n * It is NOT a personal-sign prefix (a personal-sign write with this value recovers a phantom\n * signer; use `personalSignPrefixFor`). Under EIP-712 the field is an untyped extra that the\n * typed-data hash ignores and the backend recomputes, so it only exists to keep the submitted\n * body byte-identical to what the gSwap web app has always sent.\n */\nexport function fixpointPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n let payloadLength = textEncoder.encode(getPayloadToSign(withoutPrefix)).length;\n let prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n let previousLength = -1;\n while (payloadLength !== previousLength) {\n previousLength = payloadLength;\n prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n payloadLength = textEncoder.encode(getPayloadToSign({ ...withoutPrefix, prefix })).length;\n }\n return prefix;\n}\n\nfunction invalidPrivateKey(reason: InvalidPrivateKeyReason): GalaSDKError<'INVALID_PRIVATE_KEY'> {\n return new GalaSDKError('INVALID_PRIVATE_KEY', { reason });\n}\n\nconst BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nfunction decodeBase64(input: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(input) || input.length % 4 !== 0) return undefined;\n const unpadded = input.replace(/=+$/u, '');\n const bytes: number[] = [];\n let buffer = 0;\n let bits = 0;\n for (const char of unpadded) {\n buffer = (buffer << 6) | BASE64_ALPHABET.indexOf(char);\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((buffer >> bits) & 0xff);\n }\n }\n return Uint8Array.from(bytes);\n}\n\nfunction decodeHex(input: string): Uint8Array {\n const bytes = new Uint8Array(input.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = parseInt(input.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Normalizes a secp256k1 private key to a fresh 32-byte array (the caller may zero it). Also\n * accepts 32 raw bytes, which are validated and copied. For strings it accepts what `@gala-chain/api`'s\n * `normalizePrivateKey` accepted for a usable key: 64 hex characters (optionally `0x`-prefixed;\n * a 63-character hex key is left-padded with a zero) or a 44-character base64 string.\n *\n * @throws GalaSDKError (`INVALID_PRIVATE_KEY`; `params.reason` is one of\n * `INVALID_PRIVATE_KEY_REASONS`: `wrong_length` for raw bytes that are not 32 long,\n * `bad_encoding` for any other string shape, `not_on_curve` for an out-of-range scalar).\n */\nexport function normalizePrivateKey(input: string | Uint8Array): Uint8Array {\n if (typeof input !== 'string') {\n // Raw bytes: validated, then COPIED, so zeroing the result never touches the caller's array.\n if (!(input instanceof Uint8Array) || input.length !== 32) {\n throw invalidPrivateKey('wrong_length');\n }\n if (!secp256k1.utils.isValidSecretKey(input)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return Uint8Array.from(input);\n }\n const withoutPrefix = input.startsWith('0x') ? input.slice(2) : input;\n let key: Uint8Array | undefined;\n if (/^[0-9a-fA-F]{63,64}$/u.test(withoutPrefix)) {\n key = decodeHex(withoutPrefix.length === 63 ? `0${withoutPrefix}` : withoutPrefix);\n } else if (withoutPrefix.length === 44) {\n key = decodeBase64(withoutPrefix);\n }\n if (key?.length !== 32) {\n throw invalidPrivateKey('bad_encoding');\n }\n if (!secp256k1.utils.isValidSecretKey(key)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return key;\n}\n\n/**\n * Signs a 32-byte keccak256 hash and returns GalaChain's recoverable signature: 64 hex `r` +\n * 64 hex `s` + `1b`/`1c` (`v`), lowercase, no `0x`. Deterministic (RFC 6979) and low-S, exactly\n * what `@gala-chain/api` and the Gala Wallet produce. A DER signature carries no recovery byte\n * and cannot be used: the chain RECOVERS the signer from the signature.\n */\nexport function signHash(privateKey: Uint8Array, hash: Uint8Array): string {\n if (hash.length !== 32) {\n throw new GalaSDKError('INVALID_SIGNING_HASH_LENGTH', { length: hash.length });\n }\n const signature = secp256k1.sign(hash, privateKey, { prehash: false, lowS: true });\n // compact raw bytes are r (32) || s (32); the recovery id becomes v.\n return bytesToHex(signature.toBytes('compact')) + (signature.recovery === 1 ? '1c' : '1b');\n}\n\n/**\n * The lowercase `0x` Ethereum address (last 20 bytes of keccak256 of the uncompressed public key)\n * of a normalized private key. The Gala `eth|` identity of a key is this address.\n */\nexport function ethAddressOfPrivateKey(privateKey: Uint8Array): string {\n const publicKey = secp256k1.getPublicKey(privateKey, false);\n return `0x${bytesToHex(keccak_256(publicKey.slice(1)).slice(-20))}`;\n}\n\n/** keccak256 of a string's UTF-8 bytes. */\nexport function keccak256Utf8(data: string): Uint8Array {\n return keccak_256(textEncoder.encode(data));\n}\n\n/**\n * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes, with no\n * prefix and no signature envelope. The caller owns serialization, so the bytes shown to a user\n * and the bytes signed can never diverge.\n */\nexport function signSerializedNative(privateKey: Uint8Array, serializedDto: string): string {\n return signHash(privateKey, keccak256Utf8(serializedDto));\n}\n\n/**\n * GalaChain NATIVE signature for a DTO: keccak256 of `getPayloadToSign(dto)`, signed with\n * secp256k1. Byte-identical to `signatures.getSignature` from `@gala-chain/api`.\n */\nexport function signNative(privateKey: Uint8Array, dto: Record<string, unknown>): string {\n return signSerializedNative(privateKey, getPayloadToSign(dto));\n}\n\n/**\n * Personal-sign hash and signature: keccak256(`prefix` + `message`), both hashed VERBATIM with no\n * further EIP-191 wrapping. Passing `prefix = calculatePersonalSignPrefix(message)` reproduces a\n * wallet's `personal_sign` of `message`. Gala Wallet's `gala_signChainDto` (personal-sign\n * scheme) hashes `prefix` + the exact string it is handed, which can differ from the bare message\n * (see the `signatureOverPrefixlessBody` vectors); that quirk is why the two inputs stay separate.\n */\nexport function signPersonalMessage(\n privateKey: Uint8Array,\n prefix: string,\n message: string,\n): string {\n return signHash(privateKey, keccak256Utf8(prefix + message));\n}\n"],"mappings":"A,iNAmBA,MAAMA,EAAc,IAAI,YAExB,SAASC,EAAoB,EAAwB,CACnD,GAAIC,GAAS,KAA4B,OAAOA,EAChD,GAAIA,aAAgB,OAAQ,OAAOA,EAAK,SAAS,EACjD,IAAMC,EAAYD,EAClB,OAAO,OAAOC,EAAU,QAAW,WAC9B,QAAQ,MAAMA,EAAU,OAAQD,EAAM,CAAC,CAAC,EACzCA,CACN,CAEA,SAASE,EAAkB,EAAsC,CAC/D,IAAMF,EAAOD,EAAoBI,CAAO,EACxC,GAAIH,IAAS,IAAA,GAAW,OACxB,GAAI,OAAOA,GAAS,WAAYA,EAAe,OAAO,KAAK,UAAUA,CAAI,EAEzE,GAAI,MAAM,QAAQA,CAAI,EAEpB,MAAO,IADQA,EAAmB,IAAK,GAASE,EAAkBE,CAAI,GAAK,MAC5D,CAAC,CAAC,KAAK,GAAG,EAAE,GAG7B,IAAMC,EAASL,EACTM,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAO,OAAO,KAAKF,CAAM,CAAC,CAAC,KAAK,EAAG,CAC5C,IAAMG,EAAQN,EAAkBG,EAAO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AQA,SAAgBiC,EAAS,EAAwB,EAA0B,CACzE,GAAIC,EAAK,SAAW,GAClB,MAAM,IAAIb,EAAa,8BAA+B,CAAE,OAAQa,EAAK,MAAO,CAAC,EAE/E,IAAMC,EAAYH,EAAU,KAAKE,EAAME,EAAY,CAAE,QAAS,GAAO,KAAM,EAAK,CAAC,EAEjF,OAAOC,EAAWF,EAAU,QAAQ,SAAS,CAAC,GAAKA,EAAU,WAAa,EAAI,KAAO,KACvF,CAMA,SAAgBG,EAAuB,EAAgC,CACrE,IAAMC,EAAYP,EAAU,aAAaI,EAAY,EAAK,EAC1D,MAAO,KAAKC,EAAWG,EAAWD,EAAU,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,GAClE,CAGA,SAAgBE,EAAc,EAA0B,CACtD,OAAOD,EAAWjD,EAAY,OAAOmD,CAAI,CAAC,CAC5C,CAOA,SAAgBC,EAAqB,EAAwB,EAA+B,CAC1F,OAAOV,EAASG,EAAYK,EAAcG,CAAa,CAAC,CAC1D,CAMA,SAAgBC,EAAW,EAAwB,EAAsC,CACvF,OAAOF,EAAqBP,EAAYhC,EAAiBE,CAAG,CAAC,CAC/D,CASA,SAAgBwC,EACd,EACA,EACA,EACQ,CACR,OAAOb,EAASG,EAAYK,EAAc/B,EAASG,CAAO,CAAC,CAC7D,C"}
@@ -1,2 +1,2 @@
1
- import{GalaSDKError as e,isGalaError as t,parseJson as n}from"../classes/gala_sdk_error.js";import"../version.js";function r(e,t){if(t===1/0)return()=>void 0;let n=setTimeout(()=>e.abort(),t);return()=>clearTimeout(n)}function i(t,n){if(t===1/0||Number.isFinite(t)&&t>0)return t;throw new e(`INVALID_TIMEOUT`,{field:n,value:t})}const a=/[A-Za-z0-9\-._~!'()*$|:,]/u;function o(e){let t=``;for(let n of e)n===` `?t+=`+`:a.test(n)?t+=n:t+=s(n);return t}function s(e){try{return encodeURIComponent(e)}catch{return`%EF%BF%BD`}}function c(e,t=`standard`){return t===`readable`?Object.entries(e).map(([e,t])=>`${o(e)}=${o(t)}`).join(`&`):new URLSearchParams(e).toString()}function l(e,t={}){let n=/* @__PURE__ */ new Map,r=(e,t=!1)=>{for(let[r,i]of Object.entries(e??{}))t&&n.delete(r.toLowerCase()),n.set(r.toLowerCase(),[r,i])};return e?.userAgent!==!1&&r({"User-Agent":e?.userAgent??`GalaChain-SDK/1.0.0`}),r(t.defaults),r(e?.headers),t.json===!0&&!n.has(`content-type`)&&r({"Content-Type":`application/json`}),r(t.fixed,!0),Object.fromEntries(n.values())}const u=async(t,n)=>{try{return await fetch(t,n)}catch(r){throw n?.signal?.aborted===!0?r:new e(`TRANSPORT_ERROR`,{url:t},{url:t,cause:r})}};async function d(n,i,a,o,s){let c=new AbortController,l=r(c,o),u=a.signal,d=()=>c.abort();u?.addEventListener(`abort`,d,{once:!0});let f=s?.write===!1;try{return await n(i,{...a,signal:c.signal})}catch(n){throw u?.aborted===!0?n:c.signal.aborted?new e(`REQUEST_TIMEOUT`,{url:i,timeoutMs:o},{url:i,cause:n,...f?{write:!1}:{}}):f&&t(n,`TRANSPORT_ERROR`)&&n.write?new e(`TRANSPORT_ERROR`,{url:n.url??i},{url:n.url??i,cause:n.cause,write:!1}):n}finally{l(),u?.removeEventListener(`abort`,d)}}async function f(e){let t=await e.text();return n(t)??t}function p(e,t){let n=e.headers;if(n===void 0)return;if(g(n)){let e=n.get(t);return e===null||e===``?void 0:e}let r=Object.entries(n).find(([e])=>e.toLowerCase()===t.toLowerCase())?.[1];return r===void 0||r===``?void 0:r}function m(e){let t=p(e,`retry-after`);if(t===void 0)return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}function h(e,t=`x-block-number`){let n=p(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function g(e){return`get`in e&&typeof e.get==`function`}export{r as armTimeout,c as buildQueryString,l as buildRequestHeaders,u as fetchRequestor,h as readBlockNumberHeader,p as readHeader,f as readResponseBody,m as readRetryAfter,d as requestWithTimeout,i as validateTimeoutMs};
1
+ import{GalaSDKError as e,isGalaError as t,parseJson as n}from"../classes/gala_sdk_error.js";import"../version.js";function r(e,t){if(t===1/0)return()=>void 0;let n=setTimeout(()=>e.abort(),t);return()=>clearTimeout(n)}function i(t,n){if(t===1/0||Number.isFinite(t)&&t>0)return t;throw new e(`INVALID_TIMEOUT`,{field:n,value:t})}const a=/[A-Za-z0-9\-._~!'()*$|:,]/u;function o(e){let t=``;for(let n of e)n===` `?t+=`+`:a.test(n)?t+=n:t+=s(n);return t}function s(e){try{return encodeURIComponent(e)}catch{return`%EF%BF%BD`}}function c(e,t=`standard`){return t===`readable`?Object.entries(e).map(([e,t])=>`${o(e)}=${o(t)}`).join(`&`):new URLSearchParams(e).toString()}function l(e,t={}){let n=/* @__PURE__ */ new Map,r=(e,t=!1)=>{for(let[r,i]of Object.entries(e??{}))t&&n.delete(r.toLowerCase()),n.set(r.toLowerCase(),[r,i])};return e?.userAgent!==!1&&r({"User-Agent":e?.userAgent??`GalaChain-SDK/1.1.0-beta.1`}),r(t.defaults),r(e?.headers),t.json===!0&&!n.has(`content-type`)&&r({"Content-Type":`application/json`}),r(t.fixed,!0),Object.fromEntries(n.values())}const u=async(t,n)=>{try{return await fetch(t,n)}catch(r){throw n?.signal?.aborted===!0?r:new e(`TRANSPORT_ERROR`,{url:t},{url:t,cause:r})}};async function d(n,i,a,o,s){let c=new AbortController,l=r(c,o),u=a.signal,d=()=>c.abort();u?.addEventListener(`abort`,d,{once:!0});let f=s?.write===!1;try{return await n(i,{...a,signal:c.signal})}catch(n){throw u?.aborted===!0?n:c.signal.aborted?new e(`REQUEST_TIMEOUT`,{url:i,timeoutMs:o},{url:i,cause:n,...f?{write:!1}:{}}):f&&t(n,`TRANSPORT_ERROR`)&&n.write?new e(`TRANSPORT_ERROR`,{url:n.url??i},{url:n.url??i,cause:n.cause,write:!1}):n}finally{l(),u?.removeEventListener(`abort`,d)}}async function f(e){let t=await e.text();return n(t)??t}function p(e,t){let n=e.headers;if(n===void 0)return;if(g(n)){let e=n.get(t);return e===null||e===``?void 0:e}let r=Object.entries(n).find(([e])=>e.toLowerCase()===t.toLowerCase())?.[1];return r===void 0||r===``?void 0:r}function m(e){let t=p(e,`retry-after`);if(t===void 0)return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}function h(e,t=`x-block-number`){let n=p(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function g(e){return`get`in e&&typeof e.get==`function`}export{r as armTimeout,c as buildQueryString,l as buildRequestHeaders,u as fetchRequestor,h as readBlockNumberHeader,p as readHeader,f as readResponseBody,m as readRetryAfter,d as requestWithTimeout,i as validateTimeoutMs};
2
2
  //# sourceMappingURL=transport.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","names":["armTimeout","timeoutMs","timer","controller","validateTimeoutMs","GalaSDKError","name","READABLE_QUERY_SAFE","encodeReadable","out","char","text","encodeScalar","buildQueryString","encoding","params","key","value","buildRequestHeaders","entries","put","headers","last","wire","parts","fetchRequestor","url","init","error","requestWithTimeout","disarm","externalSignal","options","abortFromCaller","read","kind","requestor","isGalaError","readResponseBody","response","parseJson","readHeader","hasHeaderGetter","readRetryAfter","raw","seconds","timestamp","readBlockNumberHeader","headerName","blockNumber"],"sources":["../../../src/utils/transport.ts"],"sourcesContent":["import type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { GalaSDKError, isGalaError, parseJson } from '../classes/gala_sdk_error.js';\nimport { GALA_CORE_SDK_VERSION } from '../version.js';\n\n/**\n * Arms the abort timer for a request. `Infinity` means \"never time out\": `setTimeout` would turn\n * it into 1 ms, so no timer is armed at all. Returns a function that disarms it.\n */\nexport function armTimeout(controller: AbortController, timeoutMs: number): () => void {\n if (timeoutMs === Infinity) return () => undefined;\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return () => clearTimeout(timer);\n}\n\n/**\n * Validates a request timeout in milliseconds: a positive finite number, or `Infinity` for none.\n *\n * @throws GalaSDKError `INVALID_TIMEOUT` (`params.field` = `name`) otherwise.\n */\nexport function validateTimeoutMs(timeoutMs: number, name: string): number {\n if (timeoutMs === Infinity || (Number.isFinite(timeoutMs) && timeoutMs > 0)) return timeoutMs;\n throw new GalaSDKError('INVALID_TIMEOUT', { field: name, value: timeoutMs });\n}\n\nconst READABLE_QUERY_SAFE = /[A-Za-z0-9\\-._~!'()*$|:,]/u;\n\nfunction encodeReadable(text: string): string {\n let out = '';\n for (const char of text) {\n if (char === ' ') out += '+';\n else if (READABLE_QUERY_SAFE.test(char)) out += char;\n else out += encodeScalar(char);\n }\n return out;\n}\n\n/** Percent-encodes one code point; a lone surrogate becomes U+FFFD, as `URLSearchParams` does. */\nfunction encodeScalar(char: string): string {\n try {\n return encodeURIComponent(char);\n } catch {\n return '%EF%BF%BD';\n }\n}\n\n/** Serializes GET parameters, in insertion order, in the encoding the wire options select. */\nexport function buildQueryString(\n params: Record<string, string>,\n encoding: WireOptions['queryEncoding'] = 'standard',\n): string {\n if (encoding === 'readable') {\n return Object.entries(params)\n .map(([key, value]) => `${encodeReadable(key)}=${encodeReadable(value)}`)\n .join('&');\n }\n return new URLSearchParams(params).toString();\n}\n\n/** What an SDK request adds to the headers the wire options describe. */\nexport interface RequestHeaderParts {\n /** The request carries a JSON body: `Content-Type: application/json` unless `wire.headers` sets one. */\n json?: boolean | undefined;\n /** Headers the SDK sends unless `wire.headers` replaces them (for example `Accept`). */\n defaults?: Record<string, string> | undefined;\n /**\n * Headers that carry the request's meaning (`X-Wallet-Address`, `X-Shadow`). They come last and\n * replace a same-named `wire.headers` entry, so an app's static headers can never re-attribute\n * or un-shadow a write.\n */\n fixed?: Record<string, string> | undefined;\n}\n\n/**\n * The request headers for ANY SDK request, GET or POST, from one place so the wire options reach\n * every request alike. Order, which is the order the requestor sees them in: `User-Agent`\n * (`wire.userAgent`, default `GalaChain-SDK/<version>`, `false` omits it), `parts.defaults`,\n * `wire.headers`, `Content-Type` (JSON bodies only), `parts.fixed`. A later entry replaces an\n * earlier one of the same name regardless of case, so a header is never sent twice.\n */\nexport function buildRequestHeaders(\n wire: WireOptions | undefined,\n parts: RequestHeaderParts = {},\n): Record<string, string> {\n const entries = new Map<string, [name: string, value: string]>();\n const put = (headers: Record<string, string> | undefined, last = false): void => {\n for (const [name, value] of Object.entries(headers ?? {})) {\n // A fixed header leaves any earlier same-named entry behind, so it also keeps its place at the end.\n if (last) entries.delete(name.toLowerCase());\n entries.set(name.toLowerCase(), [name, value]);\n }\n };\n if (wire?.userAgent !== false) {\n put({ 'User-Agent': wire?.userAgent ?? `GalaChain-SDK/${GALA_CORE_SDK_VERSION}` });\n }\n put(parts.defaults);\n put(wire?.headers);\n if (parts.json === true && !entries.has('content-type')) {\n put({ 'Content-Type': 'application/json' });\n }\n put(parts.fixed, true);\n return Object.fromEntries(entries.values());\n}\n\n/**\n * The default requestor: the global `fetch`, with a failure before any answer (offline, DNS,\n * CORS) coded as `TRANSPORT_ERROR` and the original error kept as `cause`. An aborted request is\n * left to {@link requestWithTimeout}, which knows whether the timeout or the caller aborted it.\n * A requestor the app supplies is not wrapped: its rejection reaches the caller unchanged.\n */\nexport const fetchRequestor: HttpRequestor = async (url, init) => {\n try {\n return await fetch(url, init);\n } catch (error: unknown) {\n if (init?.signal?.aborted === true) throw error;\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause: error });\n }\n};\n\n/** What a request is, for the failures the transport raises itself (see {@link requestWithTimeout}). */\nexport interface RequestKind {\n /** `false` for a read: nothing it sends is applied, so its failures say `write: false`. */\n write: boolean;\n}\n\n/**\n * Sends one request through `requestor`, aborting it after `timeoutMs` (`REQUEST_TIMEOUT`). The\n * caller's own abort passes through as it is. `kind: { write: false }` marks a read: its\n * `REQUEST_TIMEOUT`, and a `TRANSPORT_ERROR` of the default requestors (which cannot tell a read\n * from a write), then say `write: false`. Without it they are judged as a write's (fail-closed),\n * which is what a write's transport needs before it decides what an unanswered write means.\n */\nexport async function requestWithTimeout(\n requestor: HttpRequestor,\n url: string,\n options: RequestInit,\n timeoutMs: number,\n kind?: RequestKind,\n): Promise<HTTPResponse> {\n const controller = new AbortController();\n const disarm = armTimeout(controller, timeoutMs);\n const externalSignal = options.signal;\n const abortFromCaller = (): void => controller.abort();\n externalSignal?.addEventListener('abort', abortFromCaller, { once: true });\n const read = kind?.write === false;\n try {\n return await requestor(url, { ...options, signal: controller.signal });\n } catch (error: unknown) {\n // The caller's own abort is theirs: it passes through as the abort it is, never as a timeout.\n if (externalSignal?.aborted === true) throw error;\n if (controller.signal.aborted) {\n throw new GalaSDKError(\n 'REQUEST_TIMEOUT',\n { url, timeoutMs },\n { url, cause: error, ...(read ? { write: false } : {}) },\n );\n }\n if (read && isGalaError(error, 'TRANSPORT_ERROR') && error.write) {\n throw new GalaSDKError(\n 'TRANSPORT_ERROR',\n { url: error.url ?? url },\n { url: error.url ?? url, cause: error.cause, write: false },\n );\n }\n // Anything else is the requestor's own rejection (an app's axios interceptor error, say):\n // rethrown as it is, because the app's error handling produced it.\n throw error;\n } finally {\n disarm();\n externalSignal?.removeEventListener('abort', abortFromCaller);\n }\n}\n\nexport async function readResponseBody(response: HTTPResponse): Promise<unknown> {\n const text = await response.text();\n return parseJson(text) ?? text;\n}\n\n/** Read a case-insensitive response header from either supported header shape. */\nexport function readHeader(response: HTTPResponse, name: string): string | undefined {\n const headers = response.headers;\n if (headers === undefined) return undefined;\n if (hasHeaderGetter(headers)) {\n const value = headers.get(name);\n return value === null || value === '' ? undefined : value;\n }\n const value = Object.entries(headers).find(\n ([key]) => key.toLowerCase() === name.toLowerCase(),\n )?.[1];\n return value === undefined || value === '' ? undefined : value;\n}\n\n/** Read a Retry-After header (delta-seconds or an HTTP date) as non-negative milliseconds. */\nexport function readRetryAfter(response: HTTPResponse): number | undefined {\n const raw = readHeader(response, 'retry-after');\n if (raw === undefined) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const timestamp = Date.parse(raw);\n return Number.isNaN(timestamp) ? undefined : Math.max(0, timestamp - Date.now());\n}\n\n/** Read a non-negative integer block number header. */\nexport function readBlockNumberHeader(\n response: HTTPResponse,\n headerName = 'x-block-number',\n): number | undefined {\n const raw = readHeader(response, headerName);\n if (raw === undefined) return undefined;\n const blockNumber = Number(raw);\n return Number.isInteger(blockNumber) && blockNumber >= 0 ? blockNumber : undefined;\n}\n\nfunction hasHeaderGetter(\n headers: NonNullable<HTTPResponse['headers']>,\n): headers is { get(name: string): string | null } {\n return 'get' in headers && typeof headers.get === 'function';\n}\n"],"mappings":"kHASA,SAAgBA,EAAW,EAA6B,EAA+B,CACrF,GAAIC,IAAc,IAAU,UAAa,IAAA,GACzC,IAAMC,EAAQ,eAAiBC,EAAW,MAAM,EAAGF,CAAS,EAC5D,UAAa,aAAaC,CAAK,CACjC,CAOA,SAAgBE,EAAkB,EAAmB,EAAsB,CACzE,GAAIH,IAAc,KAAa,OAAO,SAASA,CAAS,GAAKA,EAAY,EAAI,OAAOA,EACpF,MAAM,IAAII,EAAa,kBAAmB,CAAE,MAAOC,EAAM,MAAOL,CAAU,CAAC,CAC7E,CAEA,MAAMM,EAAsB,6BAE5B,SAASC,EAAe,EAAsB,CAC5C,IAAIC,EAAM,GACV,IAAK,IAAMC,KAAQC,EACbD,IAAS,IAAK,GAAO,IAChBH,EAAoB,KAAKG,CAAI,EAAG,GAAOA,EAC3C,GAAOE,EAAaF,CAAI,EAE/B,OAAOD,CACT,CAGA,SAASG,EAAa,EAAsB,CAC1C,GAAI,CACF,OAAO,mBAAmBF,CAAI,CAChC,MAAQ,CACN,MAAO,WACT,CACF,CAGA,SAAgBG,EACd,EACA,EAAyC,WACjC,CAMR,OALIC,IAAa,WACR,OAAO,QAAQC,CAAM,CAAC,CAC1B,KAAK,C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G,EAC1B,GAAI,OAAO,SAASC,CAAO,GAAKA,GAAW,EAAG,OAAOA,EAAU,IAC/D,IAAMC,EAAY,KAAK,MAAMF,CAAG,EAChC,OAAO,OAAO,MAAME,CAAS,EAAI,IAAA,GAAY,KAAK,IAAI,EAAGA,EAAY,KAAK,IAAI,CAAC,CACjF,CAGA,SAAgBC,EACd,EACA,EAAa,iBACO,CACpB,IAAMH,EAAMH,EAAWF,EAAUS,CAAU,EAC3C,GAAIJ,IAAQ,IAAA,GAAW,OACvB,IAAMK,EAAc,OAAOL,CAAG,EAC9B,OAAO,OAAO,UAAUK,CAAW,GAAKA,GAAe,EAAIA,EAAc,IAAA,EAC3E,CAEA,SAASP,EACP,EACiD,CACjD,MAAO,QAASrB,GAAW,OAAOA,EAAQ,KAAQ,UACpD"}
1
+ {"version":3,"file":"transport.js","names":["armTimeout","timeoutMs","timer","controller","validateTimeoutMs","GalaSDKError","name","READABLE_QUERY_SAFE","encodeReadable","out","char","text","encodeScalar","buildQueryString","encoding","params","key","value","buildRequestHeaders","entries","put","headers","last","wire","parts","fetchRequestor","url","init","error","requestWithTimeout","disarm","externalSignal","options","abortFromCaller","read","kind","requestor","isGalaError","readResponseBody","response","parseJson","readHeader","hasHeaderGetter","readRetryAfter","raw","seconds","timestamp","readBlockNumberHeader","headerName","blockNumber"],"sources":["../../../src/utils/transport.ts"],"sourcesContent":["import type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { GalaSDKError, isGalaError, parseJson } from '../classes/gala_sdk_error.js';\nimport { GALA_CORE_SDK_VERSION } from '../version.js';\n\n/**\n * Arms the abort timer for a request. `Infinity` means \"never time out\": `setTimeout` would turn\n * it into 1 ms, so no timer is armed at all. Returns a function that disarms it.\n */\nexport function armTimeout(controller: AbortController, timeoutMs: number): () => void {\n if (timeoutMs === Infinity) return () => undefined;\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return () => clearTimeout(timer);\n}\n\n/**\n * Validates a request timeout in milliseconds: a positive finite number, or `Infinity` for none.\n *\n * @throws GalaSDKError `INVALID_TIMEOUT` (`params.field` = `name`) otherwise.\n */\nexport function validateTimeoutMs(timeoutMs: number, name: string): number {\n if (timeoutMs === Infinity || (Number.isFinite(timeoutMs) && timeoutMs > 0)) return timeoutMs;\n throw new GalaSDKError('INVALID_TIMEOUT', { field: name, value: timeoutMs });\n}\n\nconst READABLE_QUERY_SAFE = /[A-Za-z0-9\\-._~!'()*$|:,]/u;\n\nfunction encodeReadable(text: string): string {\n let out = '';\n for (const char of text) {\n if (char === ' ') out += '+';\n else if (READABLE_QUERY_SAFE.test(char)) out += char;\n else out += encodeScalar(char);\n }\n return out;\n}\n\n/** Percent-encodes one code point; a lone surrogate becomes U+FFFD, as `URLSearchParams` does. */\nfunction encodeScalar(char: string): string {\n try {\n return encodeURIComponent(char);\n } catch {\n return '%EF%BF%BD';\n }\n}\n\n/** Serializes GET parameters, in insertion order, in the encoding the wire options select. */\nexport function buildQueryString(\n params: Record<string, string>,\n encoding: WireOptions['queryEncoding'] = 'standard',\n): string {\n if (encoding === 'readable') {\n return Object.entries(params)\n .map(([key, value]) => `${encodeReadable(key)}=${encodeReadable(value)}`)\n .join('&');\n }\n return new URLSearchParams(params).toString();\n}\n\n/** What an SDK request adds to the headers the wire options describe. */\nexport interface RequestHeaderParts {\n /** The request carries a JSON body: `Content-Type: application/json` unless `wire.headers` sets one. */\n json?: boolean | undefined;\n /** Headers the SDK sends unless `wire.headers` replaces them (for example `Accept`). */\n defaults?: Record<string, string> | undefined;\n /**\n * Headers that carry the request's meaning (`X-Wallet-Address`, `X-Shadow`). They come last and\n * replace a same-named `wire.headers` entry, so an app's static headers can never re-attribute\n * or un-shadow a write.\n */\n fixed?: Record<string, string> | undefined;\n}\n\n/**\n * The request headers for ANY SDK request, GET or POST, from one place so the wire options reach\n * every request alike. Order, which is the order the requestor sees them in: `User-Agent`\n * (`wire.userAgent`, default `GalaChain-SDK/<version>`, `false` omits it), `parts.defaults`,\n * `wire.headers`, `Content-Type` (JSON bodies only), `parts.fixed`. A later entry replaces an\n * earlier one of the same name regardless of case, so a header is never sent twice.\n */\nexport function buildRequestHeaders(\n wire: WireOptions | undefined,\n parts: RequestHeaderParts = {},\n): Record<string, string> {\n const entries = new Map<string, [name: string, value: string]>();\n const put = (headers: Record<string, string> | undefined, last = false): void => {\n for (const [name, value] of Object.entries(headers ?? {})) {\n // A fixed header leaves any earlier same-named entry behind, so it also keeps its place at the end.\n if (last) entries.delete(name.toLowerCase());\n entries.set(name.toLowerCase(), [name, value]);\n }\n };\n if (wire?.userAgent !== false) {\n put({ 'User-Agent': wire?.userAgent ?? `GalaChain-SDK/${GALA_CORE_SDK_VERSION}` });\n }\n put(parts.defaults);\n put(wire?.headers);\n if (parts.json === true && !entries.has('content-type')) {\n put({ 'Content-Type': 'application/json' });\n }\n put(parts.fixed, true);\n return Object.fromEntries(entries.values());\n}\n\n/**\n * The default requestor: the global `fetch`, with a failure before any answer (offline, DNS,\n * CORS) coded as `TRANSPORT_ERROR` and the original error kept as `cause`. An aborted request is\n * left to {@link requestWithTimeout}, which knows whether the timeout or the caller aborted it.\n * A requestor the app supplies is not wrapped: its rejection reaches the caller unchanged.\n */\nexport const fetchRequestor: HttpRequestor = async (url, init) => {\n try {\n return await fetch(url, init);\n } catch (error: unknown) {\n if (init?.signal?.aborted === true) throw error;\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause: error });\n }\n};\n\n/** What a request is, for the failures the transport raises itself (see {@link requestWithTimeout}). */\nexport interface RequestKind {\n /** `false` for a read: nothing it sends is applied, so its failures say `write: false`. */\n write: boolean;\n}\n\n/**\n * Sends one request through `requestor`, aborting it after `timeoutMs` (`REQUEST_TIMEOUT`). The\n * caller's own abort passes through as it is. `kind: { write: false }` marks a read: its\n * `REQUEST_TIMEOUT`, and a `TRANSPORT_ERROR` of the default requestors (which cannot tell a read\n * from a write), then say `write: false`. Without it they are judged as a write's (fail-closed),\n * which is what a write's transport needs before it decides what an unanswered write means.\n */\nexport async function requestWithTimeout(\n requestor: HttpRequestor,\n url: string,\n options: RequestInit,\n timeoutMs: number,\n kind?: RequestKind,\n): Promise<HTTPResponse> {\n const controller = new AbortController();\n const disarm = armTimeout(controller, timeoutMs);\n const externalSignal = options.signal;\n const abortFromCaller = (): void => controller.abort();\n externalSignal?.addEventListener('abort', abortFromCaller, { once: true });\n const read = kind?.write === false;\n try {\n return await requestor(url, { ...options, signal: controller.signal });\n } catch (error: unknown) {\n // The caller's own abort is theirs: it passes through as the abort it is, never as a timeout.\n if (externalSignal?.aborted === true) throw error;\n if (controller.signal.aborted) {\n throw new GalaSDKError(\n 'REQUEST_TIMEOUT',\n { url, timeoutMs },\n { url, cause: error, ...(read ? { write: false } : {}) },\n );\n }\n if (read && isGalaError(error, 'TRANSPORT_ERROR') && error.write) {\n throw new GalaSDKError(\n 'TRANSPORT_ERROR',\n { url: error.url ?? url },\n { url: error.url ?? url, cause: error.cause, write: false },\n );\n }\n // Anything else is the requestor's own rejection (an app's axios interceptor error, say):\n // rethrown as it is, because the app's error handling produced it.\n throw error;\n } finally {\n disarm();\n externalSignal?.removeEventListener('abort', abortFromCaller);\n }\n}\n\nexport async function readResponseBody(response: HTTPResponse): Promise<unknown> {\n const text = await response.text();\n return parseJson(text) ?? text;\n}\n\n/** Read a case-insensitive response header from either supported header shape. */\nexport function readHeader(response: HTTPResponse, name: string): string | undefined {\n const headers = response.headers;\n if (headers === undefined) return undefined;\n if (hasHeaderGetter(headers)) {\n const value = headers.get(name);\n return value === null || value === '' ? undefined : value;\n }\n const value = Object.entries(headers).find(\n ([key]) => key.toLowerCase() === name.toLowerCase(),\n )?.[1];\n return value === undefined || value === '' ? undefined : value;\n}\n\n/** Read a Retry-After header (delta-seconds or an HTTP date) as non-negative milliseconds. */\nexport function readRetryAfter(response: HTTPResponse): number | undefined {\n const raw = readHeader(response, 'retry-after');\n if (raw === undefined) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const timestamp = Date.parse(raw);\n return Number.isNaN(timestamp) ? undefined : Math.max(0, timestamp - Date.now());\n}\n\n/** Read a non-negative integer block number header. */\nexport function readBlockNumberHeader(\n response: HTTPResponse,\n headerName = 'x-block-number',\n): number | undefined {\n const raw = readHeader(response, headerName);\n if (raw === undefined) return undefined;\n const blockNumber = Number(raw);\n return Number.isInteger(blockNumber) && blockNumber >= 0 ? blockNumber : undefined;\n}\n\nfunction hasHeaderGetter(\n headers: NonNullable<HTTPResponse['headers']>,\n): headers is { get(name: string): string | null } {\n return 'get' in headers && typeof headers.get === 'function';\n}\n"],"mappings":"A,kHASA,SAAgBA,EAAW,EAA6B,EAA+B,CACrF,GAAIC,IAAc,IAAU,UAAa,IAAA,GACzC,IAAMC,EAAQ,eAAiBC,EAAW,MAAM,EAAGF,CAAS,EAC5D,UAAa,aAAaC,CAAK,CACjC,CAOA,SAAgBE,EAAkB,EAAmB,EAAsB,CACzE,GAAIH,IAAc,KAAa,OAAO,SAASA,CAAS,GAAKA,EAAY,EAAI,OAAOA,EACpF,MAAM,IAAII,EAAa,kBAAmB,CAAE,MAAOC,EAAM,MAAOL,CAAU,CAAC,CAC7E,CAEA,MAAMM,EAAsB,6BAE5B,SAASC,EAAe,EAAsB,CAC5C,IAAIC,EAAM,GACV,IAAK,IAAMC,KAAQC,EACbD,IAAS,IAAK,GAAO,IAChBH,EAAoB,KAAKG,CAAI,EAAG,GAAOA,EAC3C,GAAOE,EAAaF,CAAI,EAE/B,OAAOD,CACT,CAGA,SAASG,EAAa,EAAsB,CAC1C,GAAI,CACF,OAAO,mBAAmBF,CAAI,CAChC,MAAQ,CACN,MAAO,WACT,CACF,CAGA,SAAgBG,EACd,EACA,EAAyC,WACjC,CAMR,OALIC,IAAa,WACR,OAAO,QAAQC,CAAM,CAAC,CAC1B,KAAK,CAACC,EAAKC,KAAW,GAAGT,EAAeQ,CAAG,EAAE,GAAGR,EAAeS,CAAK,GAAG,CAA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AMC,EAAY,KAAK,MAAMF,CAAG,EAChC,OAAO,OAAO,MAAME,CAAS,EAAI,IAAA,GAAY,KAAK,IAAI,EAAGA,EAAY,KAAK,IAAI,CAAC,CACjF,CAGA,SAAgBC,EACd,EACA,EAAa,iBACO,CACpB,IAAMH,EAAMH,EAAWF,EAAUS,CAAU,EAC3C,GAAIJ,IAAQ,IAAA,GAAW,OACvB,IAAMK,EAAc,OAAOL,CAAG,EAC9B,OAAO,OAAO,UAAUK,CAAW,GAAKA,GAAe,EAAIA,EAAc,IAAA,EAC3E,CAEA,SAASP,EACP,EACiD,CACjD,MAAO,QAASrB,GAAW,OAAOA,EAAQ,KAAQ,UACpD,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"typed_data.js","names":["textEncoder","IDENTIFIER","TYPE_SYNTAX","BIGINT_DECIMAL","BIGINT_HEX","DOMAIN_FIELDS","concat","out","parts","total","part","offset","bigintToWord","word","rest","value","index","hexToBytes","body","hex","toBytes","GalaSDKError","toBigInt","utf8","unit","next","addressBytes","hasValidEip55Casing","leafEncoder","base","keccak_256","fixed","width","bytes","integer","signed","lower","upper","number","parseType","match","type","dimensions","dimension","parseFields","rawFields","seen","field","raw","parsed","createStructEncoder","names","rawTypes","fields","name","children","parents","list","roots","primaryType","visiting","checked","checkCircular","child","dependencies","found","encodeOne","typeHashes","sorted","dep","encodeValue","depth","item","leaf","hashStruct","typeName","typeHash","record","words","hashDomain","domain","key","hashTypedData","domainHash","payload","encoder","structHash","signTypedDataPayload","digest","withPrivateKey","privateKey","signHash"],"sources":["../../../src/utils/typed_data.ts"],"sourcesContent":["/**\n * EIP-712 (`eth_signTypedData_v4`) hashing and signing for ARBITRARY dApp typed data, built on the\n * SDK's own primitives (`@noble/curves`, `@noble/hashes`) so a wallet can sign a dApp's typed-data\n * approval without ethers. It replaces the wallet's `new ethers.Wallet(key).signTypedData(...)`\n * and is pinned to it: the golden suite reproduces every fixture signature exactly and a seeded\n * differential fuzz compares the digest and signature with ethers for every supported type.\n *\n * Compared with ethers this encoder is deliberately STRICTER (it fails closed rather than coerce):\n * `bool` accepts only a boolean, numbers accept only safe integers / decimal or `0x` strings,\n * strings must be well-formed UTF-16, struct values must be objects whose fields are their own\n * properties, and every struct, field and type name must be a plain identifier. Anything ethers\n * accepts that is NOT in that set is refused here instead of being signed in a different shape\n * from what a user reviewed.\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { hasValidEip55Casing } from './eth_address.js';\nimport { signHash } from './signing.js';\nimport { withPrivateKey, type PrivateKeyInput } from './chain_dto_signing.js';\n\n/** A typed-data payload as `eth_signTypedData_v4` carries it, minus `primaryType` (it is inferred). */\nexport interface TypedDataPayload {\n domain: Record<string, unknown>;\n /** Struct definitions WITHOUT `EIP712Domain` (see `stripEip712DomainType`). */\n types: Record<string, readonly unknown[]>;\n message: Record<string, unknown>;\n}\n\ninterface TypedField {\n name: string;\n type: string;\n}\n\nconst textEncoder = new TextEncoder();\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;\nconst TYPE_SYNTAX = /^([A-Za-z_$][A-Za-z0-9_$]*)((?:\\[(?:0|[1-9][0-9]*)?\\])*)$/u;\nconst BIGINT_DECIMAL = /^-?[0-9]+$/u;\nconst BIGINT_HEX = /^-?0x[0-9a-fA-F]+$/u;\n\n/** The EIP-712 domain members and their types, in the order ethers (and the spec) hash them. */\nconst DOMAIN_FIELDS: readonly TypedField[] = [\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n];\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction bigintToWord(value: bigint): Uint8Array {\n const word = new Uint8Array(32);\n // Every caller has bounds-checked `value` against its Solidity type, so it fits in 256 bits.\n let rest = value < 0n ? value + (1n << 256n) : value;\n for (let index = 31; index >= 0; index -= 1) {\n word[index] = Number(rest & 0xffn);\n rest >>= 8n;\n }\n return word;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const body = hex.slice(2);\n const out = new Uint8Array(body.length / 2);\n for (let index = 0; index < out.length; index += 1) {\n out[index] = parseInt(body.slice(index * 2, index * 2 + 2), 16);\n }\n return out;\n}\n\nfunction toBytes(value: unknown, what: string): Uint8Array {\n if (value instanceof Uint8Array) return value;\n if (typeof value === 'string' && /^0x(?:[0-9a-fA-F]{2})*$/u.test(value)) return hexToBytes(value);\n throw new GalaSDKError('TYPED_DATA_NOT_HEX_BYTES', { what });\n}\n\nfunction toBigInt(value: unknown, what: string): bigint {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value))\n throw new GalaSDKError('TYPED_DATA_NOT_SAFE_INTEGER', { what });\n return BigInt(value);\n }\n if (typeof value === 'string') {\n if (BIGINT_DECIMAL.test(value)) return BigInt(value);\n if (BIGINT_HEX.test(value)) {\n return value.startsWith('-') ? -BigInt(value.slice(1)) : BigInt(value);\n }\n }\n throw new GalaSDKError('TYPED_DATA_NOT_INTEGER', { what });\n}\n\nfunction utf8(value: unknown, what: string): Uint8Array {\n if (typeof value !== 'string') throw new GalaSDKError('TYPED_DATA_NOT_STRING', { what });\n for (let index = 0; index < value.length; index += 1) {\n const unit = value.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n }\n return textEncoder.encode(value);\n}\n\n/** EIP-55: a mixed-case address must carry the right checksum; all-lower / all-upper is accepted. */\nfunction addressBytes(value: unknown): Uint8Array {\n if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{40}$/u.test(value)) {\n throw new GalaSDKError('TYPED_DATA_BAD_ADDRESS', {});\n }\n if (!hasValidEip55Casing(value.slice(2))) {\n throw new GalaSDKError('TYPED_DATA_BAD_CHECKSUM', {});\n }\n return hexToBytes(value);\n}\n\ntype LeafEncoder = (value: unknown) => Uint8Array;\n\n/** The encoder for a non-struct, non-array type, or undefined when `base` is not one. */\nfunction leafEncoder(base: string): LeafEncoder | undefined {\n if (base === 'string') return (value) => keccak_256(utf8(value, 'string'));\n if (base === 'bytes') return (value) => keccak_256(toBytes(value, 'bytes'));\n if (base === 'bool') {\n return (value) => {\n if (typeof value !== 'boolean') throw new GalaSDKError('TYPED_DATA_NOT_BOOLEAN', {});\n return bigintToWord(value ? 1n : 0n);\n };\n }\n if (base === 'address') {\n return (value) => concat([new Uint8Array(12), addressBytes(value)]);\n }\n const fixed = /^bytes([1-9][0-9]?)$/u.exec(base);\n if (fixed !== null) {\n const width = Number(fixed[1]);\n // The pattern above admits no leading zero, so `String(width)` is always the digits written.\n if (width > 32) return undefined;\n return (value) => {\n const bytes = toBytes(value, base);\n if (bytes.length !== width) {\n throw new GalaSDKError('TYPED_DATA_BYTES_LENGTH', { type: base, width });\n }\n return concat([bytes, new Uint8Array(32 - width)]);\n };\n }\n const integer = /^(u?)int([1-9][0-9]*)$/u.exec(base);\n if (integer !== null) {\n const width = Number(integer[2]);\n if (width % 8 !== 0 || width > 256 || String(width) !== integer[2]) return undefined;\n const signed = integer[1] === '';\n const lower = signed ? -(1n << BigInt(width - 1)) : 0n;\n const upper = signed ? (1n << BigInt(width - 1)) - 1n : (1n << BigInt(width)) - 1n;\n return (value) => {\n const number = toBigInt(value, base);\n if (number < lower || number > upper) {\n throw new GalaSDKError('TYPED_DATA_OUT_OF_BOUNDS', { type: base });\n }\n return bigintToWord(number);\n };\n }\n return undefined;\n}\n\ninterface ParsedType {\n base: string;\n /** Array suffixes outermost-last, e.g. `uint256[2][]` is `[2, -1]` (-1 = dynamic). */\n dimensions: number[];\n}\n\nfunction parseType(type: string): ParsedType {\n const match = TYPE_SYNTAX.exec(type);\n if (match === null) throw new GalaSDKError('TYPED_DATA_UNSUPPORTED_TYPE', { type });\n // Group 2 of TYPE_SYNTAX is `(...)*` around the whole suffix run, so it always participates.\n const dimensions = [...(match[2] as string).matchAll(/\\[([0-9]*)\\]/gu)].map((dimension) =>\n dimension[1] === '' ? -1 : Number(dimension[1]),\n );\n return { base: match[1] as string, dimensions };\n}\n\nfunction parseFields(typeName: string, rawFields: readonly unknown[]): TypedField[] {\n if (!Array.isArray(rawFields)) throw new GalaSDKError('TYPED_DATA_FIELDS_NOT_LIST', { typeName });\n const seen = new Set<string>();\n return rawFields.map((raw: unknown) => {\n const field = raw as { name?: unknown; type?: unknown } | null;\n if (typeof field?.name !== 'string' || typeof field.type !== 'string') {\n throw new GalaSDKError('TYPED_DATA_FIELD_MALFORMED', { typeName });\n }\n if (!IDENTIFIER.test(field.name)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_FIELD_NAME', { name: field.name });\n }\n if (seen.has(field.name)) {\n throw new GalaSDKError('TYPED_DATA_DUPLICATE_FIELD', { name: field.name, typeName });\n }\n seen.add(field.name);\n // A bare `int` / `uint` is the 256-bit type and is hashed as `int256` / `uint256`, like ethers.\n const parsed = parseType(field.type);\n const base =\n parsed.base === 'uint' || parsed.base === 'int' ? `${parsed.base}256` : parsed.base;\n return { name: field.name, type: base + field.type.slice(parsed.base.length) };\n });\n}\n\ninterface StructEncoder {\n primaryType: string;\n hashStruct: (typeName: string, value: unknown) => Uint8Array;\n}\n\n/**\n * Builds the struct encoder for a set of type definitions: validates the type graph (unknown or\n * circular references, duplicate fields) and infers the primary type as the single type no other\n * type references, exactly like ethers' `TypedDataEncoder`.\n */\nfunction createStructEncoder(rawTypes: Record<string, readonly unknown[]>): StructEncoder {\n const names = Object.keys(rawTypes);\n const fields = new Map<string, TypedField[]>();\n for (const name of names) {\n if (!IDENTIFIER.test(name)) throw new GalaSDKError('TYPED_DATA_INVALID_TYPE_NAME', { name });\n fields.set(name, parseFields(name, rawTypes[name] as readonly unknown[]));\n }\n\n const children = new Map<string, Set<string>>();\n const parents = new Map<string, Set<string>>();\n for (const name of names) {\n children.set(name, new Set());\n parents.set(name, new Set());\n }\n for (const [name, list] of fields) {\n for (const field of list) {\n const { base } = parseType(field.type);\n if (base === name) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (leafEncoder(base) !== undefined) continue;\n if (!fields.has(base)) {\n throw new GalaSDKError('TYPED_DATA_UNKNOWN_FIELD_TYPE', { type: base, typeName: name });\n }\n children.get(name)?.add(base);\n parents.get(base)?.add(name);\n }\n }\n\n const roots = names.filter((name) => parents.get(name)?.size === 0);\n if (roots.length === 0) throw new GalaSDKError('TYPED_DATA_NO_PRIMARY_TYPE', {});\n if (roots.length > 1) {\n throw new GalaSDKError('TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE', { roots: roots.join(', ') });\n }\n const primaryType = roots[0] as string;\n\n const visiting = new Set<string>();\n const checked = new Set<string>();\n const checkCircular = (name: string): void => {\n if (visiting.has(name)) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (checked.has(name)) return;\n visiting.add(name);\n // `children` holds an entry for every name, and `name` is always one of them.\n for (const child of children.get(name) as Set<string>) checkCircular(child);\n visiting.delete(name);\n checked.add(name);\n };\n checkCircular(primaryType);\n\n const dependencies = (name: string, found: Set<string>): Set<string> => {\n for (const child of children.get(name) as Set<string>) {\n if (!found.has(child)) {\n found.add(child);\n dependencies(child, found);\n }\n }\n return found;\n };\n const encodeOne = (name: string): string =>\n `${name}(${(fields.get(name) as TypedField[]).map((field) => `${field.type} ${field.name}`).join(',')})`;\n const typeHashes = new Map<string, Uint8Array>();\n for (const name of names) {\n const sorted = [...dependencies(name, new Set())].filter((dep) => dep !== name).sort();\n typeHashes.set(name, keccak_256(textEncoder.encode([name, ...sorted].map(encodeOne).join(''))));\n }\n\n const encodeValue = (parsed: ParsedType, value: unknown, depth: number): Uint8Array => {\n // The LAST bracket written is the outermost array: `uint8[][2]` is two `uint8[]`.\n const dimension = parsed.dimensions[parsed.dimensions.length - 1 - depth];\n if (dimension !== undefined) {\n if (!Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_EXPECTED', { type: parsed.base });\n }\n if (dimension !== -1 && dimension !== value.length) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_LENGTH_MISMATCH', {});\n }\n return keccak_256(concat(value.map((item) => encodeValue(parsed, item, depth + 1))));\n }\n const leaf = leafEncoder(parsed.base);\n if (leaf !== undefined) return leaf(value);\n return hashStruct(parsed.base, value);\n };\n\n function hashStruct(typeName: string, value: unknown): Uint8Array {\n // createStructEncoder has already validated every struct name this is called with (the\n // primary type, the domain type, and each field base that is not a leaf type).\n const list = fields.get(typeName) as TypedField[];\n const typeHash = typeHashes.get(typeName) as Uint8Array;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_STRUCT_NOT_OBJECT', { typeName });\n }\n const record = value as Record<string, unknown>;\n const words = list.map((field) => {\n if (!Object.prototype.hasOwnProperty.call(record, field.name)) {\n throw new GalaSDKError('TYPED_DATA_MISSING_FIELD', { typeName, field: field.name });\n }\n // Struct-valued fields are encoded to their 32-byte struct hash by encodeValue.\n return encodeValue(parseType(field.type), record[field.name], 0);\n });\n return keccak_256(concat([typeHash, ...words]));\n }\n\n return { primaryType, hashStruct };\n}\n\nfunction hashDomain(domain: Record<string, unknown>): Uint8Array {\n if (domain === null || typeof domain !== 'object' || Array.isArray(domain)) {\n throw new GalaSDKError('TYPED_DATA_DOMAIN_NOT_OBJECT', {});\n }\n for (const key of Object.keys(domain)) {\n if (!DOMAIN_FIELDS.some((field) => field.name === key)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_DOMAIN_KEY', { key: JSON.stringify(key) });\n }\n }\n const present = DOMAIN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(domain, field.name),\n );\n const encoder = createStructEncoder({ EIP712Domain: present });\n return encoder.hashStruct('EIP712Domain', domain);\n}\n\n/**\n * The EIP-712 digest `keccak256(0x1901 || domainSeparator || hashStruct(primaryType, message))`\n * that a wallet signs for `eth_signTypedData_v4`. The primary type is inferred, as ethers does.\n *\n * @throws GalaSDKError (`TYPED_DATA_*`) for any type graph or value it cannot encode\n * exactly (see the module note on strictness).\n */\nexport function hashTypedData(payload: TypedDataPayload): Uint8Array {\n const domainHash = hashDomain(payload.domain);\n const encoder = createStructEncoder(payload.types);\n const structHash = encoder.hashStruct(encoder.primaryType, payload.message);\n return keccak_256(concat([Uint8Array.of(0x19, 0x01), domainHash, structHash]));\n}\n\n/**\n * Signs a dApp's EIP-712 typed-data approval (the wallet's `signTypedMessage` path), replacing\n * `new ethers.Wallet(key).signTypedData(domain, types, message)`. `types` must already have\n * `EIP712Domain` removed (`stripEip712DomainType`).\n *\n * @returns `0x` + r + s + v with `v` = `0x1b`/`0x1c` (27/28): ethers' serialized signature form,\n * recoverable with `verifyTypedData` / `eth_signTypedData_v4` verifiers. Rejects (never throws\n * synchronously) on invalid input.\n */\nexport async function signTypedDataPayload(\n privateKey: PrivateKeyInput,\n payload: TypedDataPayload,\n): Promise<string> {\n const digest = hashTypedData(payload);\n return withPrivateKey(privateKey, (key) => `0x${signHash(key, digest)}`);\n}\n"],"mappings":"mQAiCA,MAAMA,EAAc,IAAI,YAClBC,EAAa,8BACbC,EAAc,6DACdC,EAAiB,cACjBC,EAAa,sBAGbC,EAAuC,CAC3C,CAAE,KAAM,OAAQ,KAAM,QAAS,EAC/B,CAAE,KAAM,UAAW,KAAM,QAAS,EAClC,CAAE,KAAM,UAAW,KAAM,SAAU,EACnC,CAAE,KAAM,oBAAqB,KAAM,SAAU,EAC7C,CAAE,KAAM,OAAQ,KAAM,SAAU,CAClC,EA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AEC,CAAE,CAC/C,CAAC,CAAC,WAAW,eAAgBiC,CAAM,CAClD,CASA,SAAgBE,EAAc,EAAuC,CACnE,IAAMC,EAAaJ,EAAWK,EAAQ,MAAM,EACtCC,EAAUnC,EAAoBkC,EAAQ,KAAK,EAC3CE,EAAaD,EAAQ,WAAWA,EAAQ,YAAaD,EAAQ,OAAO,EAC1E,OAAOtD,EAAWxB,EAAO,CAAC,WAAW,GAAG,GAAM,CAAI,EAAG6E,EAAYG,CAAU,CAAC,CAAC,CAC/E,CAWA,eAAsBC,EACpB,EACA,EACiB,CACjB,IAAMC,EAASN,EAAcE,CAAO,EACpC,OAAOK,EAAeC,EAAa,GAAQ,KAAKC,EAASV,EAAKO,CAAM,GAAG,CACzE"}
1
+ {"version":3,"file":"typed_data.js","names":["textEncoder","IDENTIFIER","TYPE_SYNTAX","BIGINT_DECIMAL","BIGINT_HEX","DOMAIN_FIELDS","concat","out","parts","total","part","offset","bigintToWord","word","rest","value","index","hexToBytes","body","hex","toBytes","GalaSDKError","toBigInt","utf8","unit","next","addressBytes","hasValidEip55Casing","leafEncoder","base","keccak_256","fixed","width","bytes","integer","signed","lower","upper","number","parseType","match","type","dimensions","dimension","parseFields","rawFields","seen","field","raw","parsed","createStructEncoder","names","rawTypes","fields","name","children","parents","list","roots","primaryType","visiting","checked","checkCircular","child","dependencies","found","encodeOne","typeHashes","sorted","dep","encodeValue","depth","item","leaf","hashStruct","typeName","typeHash","record","words","hashDomain","domain","key","hashTypedData","domainHash","payload","encoder","structHash","signTypedDataPayload","digest","withPrivateKey","privateKey","signHash"],"sources":["../../../src/utils/typed_data.ts"],"sourcesContent":["/**\n * EIP-712 (`eth_signTypedData_v4`) hashing and signing for ARBITRARY dApp typed data, built on the\n * SDK's own primitives (`@noble/curves`, `@noble/hashes`) so a wallet can sign a dApp's typed-data\n * approval without ethers. It replaces the wallet's `new ethers.Wallet(key).signTypedData(...)`\n * and is pinned to it: the golden suite reproduces every fixture signature exactly and a seeded\n * differential fuzz compares the digest and signature with ethers for every supported type.\n *\n * Compared with ethers this encoder is deliberately STRICTER (it fails closed rather than coerce):\n * `bool` accepts only a boolean, numbers accept only safe integers / decimal or `0x` strings,\n * strings must be well-formed UTF-16, struct values must be objects whose fields are their own\n * properties, and every struct, field and type name must be a plain identifier. Anything ethers\n * accepts that is NOT in that set is refused here instead of being signed in a different shape\n * from what a user reviewed.\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { hasValidEip55Casing } from './eth_address.js';\nimport { signHash } from './signing.js';\nimport { withPrivateKey, type PrivateKeyInput } from './chain_dto_signing.js';\n\n/** A typed-data payload as `eth_signTypedData_v4` carries it, minus `primaryType` (it is inferred). */\nexport interface TypedDataPayload {\n domain: Record<string, unknown>;\n /** Struct definitions WITHOUT `EIP712Domain` (see `stripEip712DomainType`). */\n types: Record<string, readonly unknown[]>;\n message: Record<string, unknown>;\n}\n\ninterface TypedField {\n name: string;\n type: string;\n}\n\nconst textEncoder = new TextEncoder();\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;\nconst TYPE_SYNTAX = /^([A-Za-z_$][A-Za-z0-9_$]*)((?:\\[(?:0|[1-9][0-9]*)?\\])*)$/u;\nconst BIGINT_DECIMAL = /^-?[0-9]+$/u;\nconst BIGINT_HEX = /^-?0x[0-9a-fA-F]+$/u;\n\n/** The EIP-712 domain members and their types, in the order ethers (and the spec) hash them. */\nconst DOMAIN_FIELDS: readonly TypedField[] = [\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n];\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction bigintToWord(value: bigint): Uint8Array {\n const word = new Uint8Array(32);\n // Every caller has bounds-checked `value` against its Solidity type, so it fits in 256 bits.\n let rest = value < 0n ? value + (1n << 256n) : value;\n for (let index = 31; index >= 0; index -= 1) {\n word[index] = Number(rest & 0xffn);\n rest >>= 8n;\n }\n return word;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const body = hex.slice(2);\n const out = new Uint8Array(body.length / 2);\n for (let index = 0; index < out.length; index += 1) {\n out[index] = parseInt(body.slice(index * 2, index * 2 + 2), 16);\n }\n return out;\n}\n\nfunction toBytes(value: unknown, what: string): Uint8Array {\n if (value instanceof Uint8Array) return value;\n if (typeof value === 'string' && /^0x(?:[0-9a-fA-F]{2})*$/u.test(value)) return hexToBytes(value);\n throw new GalaSDKError('TYPED_DATA_NOT_HEX_BYTES', { what });\n}\n\nfunction toBigInt(value: unknown, what: string): bigint {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value))\n throw new GalaSDKError('TYPED_DATA_NOT_SAFE_INTEGER', { what });\n return BigInt(value);\n }\n if (typeof value === 'string') {\n if (BIGINT_DECIMAL.test(value)) return BigInt(value);\n if (BIGINT_HEX.test(value)) {\n return value.startsWith('-') ? -BigInt(value.slice(1)) : BigInt(value);\n }\n }\n throw new GalaSDKError('TYPED_DATA_NOT_INTEGER', { what });\n}\n\nfunction utf8(value: unknown, what: string): Uint8Array {\n if (typeof value !== 'string') throw new GalaSDKError('TYPED_DATA_NOT_STRING', { what });\n for (let index = 0; index < value.length; index += 1) {\n const unit = value.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n }\n return textEncoder.encode(value);\n}\n\n/** EIP-55: a mixed-case address must carry the right checksum; all-lower / all-upper is accepted. */\nfunction addressBytes(value: unknown): Uint8Array {\n if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{40}$/u.test(value)) {\n throw new GalaSDKError('TYPED_DATA_BAD_ADDRESS', {});\n }\n if (!hasValidEip55Casing(value.slice(2))) {\n throw new GalaSDKError('TYPED_DATA_BAD_CHECKSUM', {});\n }\n return hexToBytes(value);\n}\n\ntype LeafEncoder = (value: unknown) => Uint8Array;\n\n/** The encoder for a non-struct, non-array type, or undefined when `base` is not one. */\nfunction leafEncoder(base: string): LeafEncoder | undefined {\n if (base === 'string') return (value) => keccak_256(utf8(value, 'string'));\n if (base === 'bytes') return (value) => keccak_256(toBytes(value, 'bytes'));\n if (base === 'bool') {\n return (value) => {\n if (typeof value !== 'boolean') throw new GalaSDKError('TYPED_DATA_NOT_BOOLEAN', {});\n return bigintToWord(value ? 1n : 0n);\n };\n }\n if (base === 'address') {\n return (value) => concat([new Uint8Array(12), addressBytes(value)]);\n }\n const fixed = /^bytes([1-9][0-9]?)$/u.exec(base);\n if (fixed !== null) {\n const width = Number(fixed[1]);\n // The pattern above admits no leading zero, so `String(width)` is always the digits written.\n if (width > 32) return undefined;\n return (value) => {\n const bytes = toBytes(value, base);\n if (bytes.length !== width) {\n throw new GalaSDKError('TYPED_DATA_BYTES_LENGTH', { type: base, width });\n }\n return concat([bytes, new Uint8Array(32 - width)]);\n };\n }\n const integer = /^(u?)int([1-9][0-9]*)$/u.exec(base);\n if (integer !== null) {\n const width = Number(integer[2]);\n if (width % 8 !== 0 || width > 256 || String(width) !== integer[2]) return undefined;\n const signed = integer[1] === '';\n const lower = signed ? -(1n << BigInt(width - 1)) : 0n;\n const upper = signed ? (1n << BigInt(width - 1)) - 1n : (1n << BigInt(width)) - 1n;\n return (value) => {\n const number = toBigInt(value, base);\n if (number < lower || number > upper) {\n throw new GalaSDKError('TYPED_DATA_OUT_OF_BOUNDS', { type: base });\n }\n return bigintToWord(number);\n };\n }\n return undefined;\n}\n\ninterface ParsedType {\n base: string;\n /** Array suffixes outermost-last, e.g. `uint256[2][]` is `[2, -1]` (-1 = dynamic). */\n dimensions: number[];\n}\n\nfunction parseType(type: string): ParsedType {\n const match = TYPE_SYNTAX.exec(type);\n if (match === null) throw new GalaSDKError('TYPED_DATA_UNSUPPORTED_TYPE', { type });\n // Group 2 of TYPE_SYNTAX is `(...)*` around the whole suffix run, so it always participates.\n const dimensions = [...(match[2] as string).matchAll(/\\[([0-9]*)\\]/gu)].map((dimension) =>\n dimension[1] === '' ? -1 : Number(dimension[1]),\n );\n return { base: match[1] as string, dimensions };\n}\n\nfunction parseFields(typeName: string, rawFields: readonly unknown[]): TypedField[] {\n if (!Array.isArray(rawFields)) throw new GalaSDKError('TYPED_DATA_FIELDS_NOT_LIST', { typeName });\n const seen = new Set<string>();\n return rawFields.map((raw: unknown) => {\n const field = raw as { name?: unknown; type?: unknown } | null;\n if (typeof field?.name !== 'string' || typeof field.type !== 'string') {\n throw new GalaSDKError('TYPED_DATA_FIELD_MALFORMED', { typeName });\n }\n if (!IDENTIFIER.test(field.name)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_FIELD_NAME', { name: field.name });\n }\n if (seen.has(field.name)) {\n throw new GalaSDKError('TYPED_DATA_DUPLICATE_FIELD', { name: field.name, typeName });\n }\n seen.add(field.name);\n // A bare `int` / `uint` is the 256-bit type and is hashed as `int256` / `uint256`, like ethers.\n const parsed = parseType(field.type);\n const base =\n parsed.base === 'uint' || parsed.base === 'int' ? `${parsed.base}256` : parsed.base;\n return { name: field.name, type: base + field.type.slice(parsed.base.length) };\n });\n}\n\ninterface StructEncoder {\n primaryType: string;\n hashStruct: (typeName: string, value: unknown) => Uint8Array;\n}\n\n/**\n * Builds the struct encoder for a set of type definitions: validates the type graph (unknown or\n * circular references, duplicate fields) and infers the primary type as the single type no other\n * type references, exactly like ethers' `TypedDataEncoder`.\n */\nfunction createStructEncoder(rawTypes: Record<string, readonly unknown[]>): StructEncoder {\n const names = Object.keys(rawTypes);\n const fields = new Map<string, TypedField[]>();\n for (const name of names) {\n if (!IDENTIFIER.test(name)) throw new GalaSDKError('TYPED_DATA_INVALID_TYPE_NAME', { name });\n fields.set(name, parseFields(name, rawTypes[name] as readonly unknown[]));\n }\n\n const children = new Map<string, Set<string>>();\n const parents = new Map<string, Set<string>>();\n for (const name of names) {\n children.set(name, new Set());\n parents.set(name, new Set());\n }\n for (const [name, list] of fields) {\n for (const field of list) {\n const { base } = parseType(field.type);\n if (base === name) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (leafEncoder(base) !== undefined) continue;\n if (!fields.has(base)) {\n throw new GalaSDKError('TYPED_DATA_UNKNOWN_FIELD_TYPE', { type: base, typeName: name });\n }\n children.get(name)?.add(base);\n parents.get(base)?.add(name);\n }\n }\n\n const roots = names.filter((name) => parents.get(name)?.size === 0);\n if (roots.length === 0) throw new GalaSDKError('TYPED_DATA_NO_PRIMARY_TYPE', {});\n if (roots.length > 1) {\n throw new GalaSDKError('TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE', { roots: roots.join(', ') });\n }\n const primaryType = roots[0] as string;\n\n const visiting = new Set<string>();\n const checked = new Set<string>();\n const checkCircular = (name: string): void => {\n if (visiting.has(name)) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (checked.has(name)) return;\n visiting.add(name);\n // `children` holds an entry for every name, and `name` is always one of them.\n for (const child of children.get(name) as Set<string>) checkCircular(child);\n visiting.delete(name);\n checked.add(name);\n };\n checkCircular(primaryType);\n\n const dependencies = (name: string, found: Set<string>): Set<string> => {\n for (const child of children.get(name) as Set<string>) {\n if (!found.has(child)) {\n found.add(child);\n dependencies(child, found);\n }\n }\n return found;\n };\n const encodeOne = (name: string): string =>\n `${name}(${(fields.get(name) as TypedField[]).map((field) => `${field.type} ${field.name}`).join(',')})`;\n const typeHashes = new Map<string, Uint8Array>();\n for (const name of names) {\n const sorted = [...dependencies(name, new Set())].filter((dep) => dep !== name).sort();\n typeHashes.set(name, keccak_256(textEncoder.encode([name, ...sorted].map(encodeOne).join(''))));\n }\n\n const encodeValue = (parsed: ParsedType, value: unknown, depth: number): Uint8Array => {\n // The LAST bracket written is the outermost array: `uint8[][2]` is two `uint8[]`.\n const dimension = parsed.dimensions[parsed.dimensions.length - 1 - depth];\n if (dimension !== undefined) {\n if (!Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_EXPECTED', { type: parsed.base });\n }\n if (dimension !== -1 && dimension !== value.length) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_LENGTH_MISMATCH', {});\n }\n return keccak_256(concat(value.map((item) => encodeValue(parsed, item, depth + 1))));\n }\n const leaf = leafEncoder(parsed.base);\n if (leaf !== undefined) return leaf(value);\n return hashStruct(parsed.base, value);\n };\n\n function hashStruct(typeName: string, value: unknown): Uint8Array {\n // createStructEncoder has already validated every struct name this is called with (the\n // primary type, the domain type, and each field base that is not a leaf type).\n const list = fields.get(typeName) as TypedField[];\n const typeHash = typeHashes.get(typeName) as Uint8Array;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_STRUCT_NOT_OBJECT', { typeName });\n }\n const record = value as Record<string, unknown>;\n const words = list.map((field) => {\n if (!Object.prototype.hasOwnProperty.call(record, field.name)) {\n throw new GalaSDKError('TYPED_DATA_MISSING_FIELD', { typeName, field: field.name });\n }\n // Struct-valued fields are encoded to their 32-byte struct hash by encodeValue.\n return encodeValue(parseType(field.type), record[field.name], 0);\n });\n return keccak_256(concat([typeHash, ...words]));\n }\n\n return { primaryType, hashStruct };\n}\n\nfunction hashDomain(domain: Record<string, unknown>): Uint8Array {\n if (domain === null || typeof domain !== 'object' || Array.isArray(domain)) {\n throw new GalaSDKError('TYPED_DATA_DOMAIN_NOT_OBJECT', {});\n }\n for (const key of Object.keys(domain)) {\n if (!DOMAIN_FIELDS.some((field) => field.name === key)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_DOMAIN_KEY', { key: JSON.stringify(key) });\n }\n }\n const present = DOMAIN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(domain, field.name),\n );\n const encoder = createStructEncoder({ EIP712Domain: present });\n return encoder.hashStruct('EIP712Domain', domain);\n}\n\n/**\n * The EIP-712 digest `keccak256(0x1901 || domainSeparator || hashStruct(primaryType, message))`\n * that a wallet signs for `eth_signTypedData_v4`. The primary type is inferred, as ethers does.\n *\n * @throws GalaSDKError (`TYPED_DATA_*`) for any type graph or value it cannot encode\n * exactly (see the module note on strictness).\n */\nexport function hashTypedData(payload: TypedDataPayload): Uint8Array {\n const domainHash = hashDomain(payload.domain);\n const encoder = createStructEncoder(payload.types);\n const structHash = encoder.hashStruct(encoder.primaryType, payload.message);\n return keccak_256(concat([Uint8Array.of(0x19, 0x01), domainHash, structHash]));\n}\n\n/**\n * Signs a dApp's EIP-712 typed-data approval (the wallet's `signTypedMessage` path), replacing\n * `new ethers.Wallet(key).signTypedData(domain, types, message)`. `types` must already have\n * `EIP712Domain` removed (`stripEip712DomainType`).\n *\n * @returns `0x` + r + s + v with `v` = `0x1b`/`0x1c` (27/28): ethers' serialized signature form,\n * recoverable with `verifyTypedData` / `eth_signTypedData_v4` verifiers. Rejects (never throws\n * synchronously) on invalid input.\n */\nexport async function signTypedDataPayload(\n privateKey: PrivateKeyInput,\n payload: TypedDataPayload,\n): Promise<string> {\n const digest = hashTypedData(payload);\n return withPrivateKey(privateKey, (key) => `0x${signHash(key, digest)}`);\n}\n"],"mappings":"A,mQAiCA,MAAMA,EAAc,IAAI,YAClBC,EAAa,8BACbC,EAAc,6DACdC,EAAiB,cACjBC,EAAa,sBAGbC,EAAuC,CAC3C,CAAE,KAAM,OAAQ,KAAM,QAAS,EAC/B,CAAE,KAAM,UAAW,KAAM,QAAS,EAClC,CAAE,KAAM,UAAW,KAAM,SAAU,EACnC,CAAE,KAAM,oBAAqB,KAAM,SAAU,EAC7C,CAAE,KAAM,O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K2E,EAAQjC,EAAM,IAAI,CAEC,CAAE,CAC/C,CAAC,CAAC,WAAW,eAAgBiC,CAAM,CAClD,CASA,SAAgBE,EAAc,EAAuC,CACnE,IAAMC,EAAaJ,EAAWK,EAAQ,MAAM,EACtCC,EAAUnC,EAAoBkC,EAAQ,KAAK,EAC3CE,EAAaD,EAAQ,WAAWA,EAAQ,YAAaD,EAAQ,OAAO,EAC1E,OAAOtD,EAAWxB,EAAO,CAAC,WAAW,GAAG,GAAM,CAAI,EAAG6E,EAAYG,CAAU,CAAC,CAAC,CAC/E,CAWA,eAAsBC,EACpB,EACA,EACiB,CACjB,IAAMC,EAASN,EAAcE,CAAO,EACpC,OAAOK,EAAeC,EAAa,GAAQ,KAAKC,EAASV,EAAKO,CAAM,GAAG,CACzE,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"unique_key.js","names":["DEFAULT_UNIQUE_KEY_PREFIX","UNIQUE_KEY_PREFIX_PATTERN","resolveUniqueKeyPrefix","prefix","GalaSDKError","assertUniqueKey","isValidUniqueKey","uniqueKey","randomUuidV4","source","bytes","hex","value","index","byte","text","createUniqueKey"],"sources":["../../../src/utils/unique_key.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { isValidUniqueKey } from './unique_key_syntax.js';\n\n/**\n * The `uniqueKey` prefix the Gala Wallet and the gSwap web app have always sent\n * (`galaswap-operation-<uuid>`). The backend does not depend on it: the chain-write verifier\n * only requires a non-empty key of at most 256 characters, and apply-results accepts\n * `[A-Za-z0-9._:-]{1,128}`; the only code that mints a prefixed key itself is the server-side v1\n * trade builder, which nothing reads back by prefix.\n */\nexport const DEFAULT_UNIQUE_KEY_PREFIX = 'galaswap-operation-';\n\n/** Options shared by the services that mint `uniqueKey`s for writes. */\nexport interface UniqueKeyOptions {\n /**\n * Prefix of every minted `uniqueKey` (`<prefix><uuid>`). Defaults to\n * `DEFAULT_UNIQUE_KEY_PREFIX` (`galaswap-operation-`).\n */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/** A canonical UUID is 36 characters; the apply-results key limit is 128. */\nconst MAX_UNIQUE_KEY_PREFIX_LENGTH = 128 - 36;\nconst UNIQUE_KEY_PREFIX_PATTERN = /^[A-Za-z0-9._:-]*$/u;\n\n/**\n * Validates a caller-supplied `uniqueKey` prefix. The whole key (`<prefix><uuid>`) must stay a\n * valid apply-results key, otherwise `confirm()` could never read the outcome of the write.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY_PREFIX` when the prefix has characters outside\n * `A-Za-z0-9._:-` or is longer than 92 characters.\n */\nexport function resolveUniqueKeyPrefix(prefix: string | undefined): string {\n if (prefix === undefined) return DEFAULT_UNIQUE_KEY_PREFIX;\n if (!UNIQUE_KEY_PREFIX_PATTERN.test(prefix) || prefix.length > MAX_UNIQUE_KEY_PREFIX_LENGTH) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY_PREFIX', {\n uniqueKeyPrefix: prefix,\n maxLength: MAX_UNIQUE_KEY_PREFIX_LENGTH,\n });\n }\n return prefix;\n}\n\n/**\n * Validates a caller-supplied write `uniqueKey`: 1 to 128 characters of `A-Za-z0-9._:-`, the\n * shape the apply-results route accepts, so the write's outcome can always be read back with\n * `confirm()`. A key is one attempt's identity: reuse it only to retry that same attempt.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY` otherwise.\n */\nexport function assertUniqueKey(uniqueKey: string): void {\n if (!isValidUniqueKey(uniqueKey)) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY', { uniqueKey: String(uniqueKey) });\n }\n}\n\n/** The part of `globalThis.crypto` a uniqueKey needs: the one CSPRNG every target can offer. */\ninterface RandomValuesSource {\n getRandomValues?: ((array: Uint8Array) => unknown) | undefined;\n}\n\n/**\n * A random version-4 UUID (RFC 9562) in the canonical lowercase `8-4-4-4-12` form, byte for byte\n * the shape `crypto.randomUUID()` returns, built from `crypto.getRandomValues`. `randomUUID` is\n * NOT used: React Native's Hermes has no `crypto.randomUUID`, so a write would fail with\n * \"undefined is not a function\", while `getRandomValues` is what browsers, Node (>= 19 as a\n * global), MV3 service workers and Hermes with `react-native-get-random-values` all provide.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when there is no `getRandomValues`: a key minted from\n * `Math.random` could collide with another attempt's, so the SDK refuses rather than degrade.\n */\nfunction randomUuidV4(): string {\n const source = (globalThis as { crypto?: RandomValuesSource | undefined }).crypto;\n if (typeof source?.getRandomValues !== 'function') {\n throw new GalaSDKError('CSPRNG_UNAVAILABLE', {});\n }\n // Filled in place: a polyfill is not relied on to return the array.\n const bytes = new Uint8Array(16);\n source.getRandomValues(bytes);\n const hex: string[] = [];\n bytes.forEach((byte, index) => {\n // Version nibble 4 in byte 6, variant bits 10 in byte 8; everything else stays random.\n const value = index === 6 ? (byte & 0x0f) | 0x40 : index === 8 ? (byte & 0x3f) | 0x80 : byte;\n hex.push(value.toString(16).padStart(2, '0'));\n });\n const text = hex.join('');\n return [\n text.slice(0, 8),\n text.slice(8, 12),\n text.slice(12, 16),\n text.slice(16, 20),\n text.slice(20),\n ].join('-');\n}\n\n/**\n * A fresh per-attempt key: `<prefix><random UUID>`, the UUID a random version-4 one.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when the platform has no `crypto.getRandomValues`\n * (install a polyfill such as `react-native-get-random-values` on React Native).\n */\nexport function createUniqueKey(prefix: string): string {\n return `${prefix}${randomUuidV4()}`;\n}\n"],"mappings":"sHAUA,MAAaA,EAA4B,sBAanCC,EAA4B,sBASlC,SAAgBC,EAAuB,EAAoC,CACzE,GAAIC,IAAW,IAAA,GAAW,OAAOH,EACjC,GAAI,CAACC,EAA0B,KAAKE,CAAM,GAAKA,EAAO,OAAS,GAC7D,MAAM,IAAIC,EAAa,4BAA6B,CAClD,gBAAiBD,EACjB,UAAW,EACb,CAAC,EAEH,OAAOA,CACT,CASA,SAAgBE,EAAgB,EAAyB,CACvD,GAAI,CAACC,EAAiBC,CAAS,EAC7B,MAAM,IAAIH,EAAa,qBAAsB,CAAE,UAAW,OAAOG,CAAS,CAAE,CAAC,CAEjF,CAiBA,SAASC,GAAuB,CAC9B,IAAMC,EAAU,WAA2D,OAC3E,GAAI,OAAOA,GAAQ,iBAAoB,WACrC,MAAM,IAAIL,EAAa,qBAAsB,CAAC,CAAC,EAGjD,IAAMM,kBAAQ,IAAI,WAAW,EAAE,EAC/BD,EAAO,gBAAgBC,CAAK,EAC5B,IAAMC,EAAgB,CAAC,EACvBD,EAAM,SAAS,EAAM,IAAU,CAE7B,IAAME,EAAQC,IAAU,EAAKC,EAAO,GAAQ,GAAOD,IAAU,EAAKC,EAAO,GAAQ,IAAOA,EACxFH,EAAI,KAAKC,EAAM,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAC9C,CAAC,EACD,IAAMG,EAAOJ,EAAI,KAAK,EAAE,EACxB,MAAO,CACLI,EAAK,MAAM,EAAG,CAAC,EACfA,EAAK,MAAM,EAAG,EAAE,EAChBA,EAAK,MAAM,GAAI,EAAE,EACjBA,EAAK,MAAM,GAAI,EAAE,EACjBA,EAAK,MAAM,EAAE,CACf,CAAC,CAAC,KAAK,GAAG,CACZ,CAQA,SAAgBC,EAAgB,EAAwB,CACtD,MAAO,GAAGb,IAASK,EAAa,GAClC"}
1
+ {"version":3,"file":"unique_key.js","names":["DEFAULT_UNIQUE_KEY_PREFIX","UNIQUE_KEY_PREFIX_PATTERN","resolveUniqueKeyPrefix","prefix","GalaSDKError","assertUniqueKey","isValidUniqueKey","uniqueKey","randomUuidV4","source","bytes","hex","value","index","byte","text","createUniqueKey"],"sources":["../../../src/utils/unique_key.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { isValidUniqueKey } from './unique_key_syntax.js';\n\n/**\n * The `uniqueKey` prefix the Gala Wallet and the gSwap web app have always sent\n * (`galaswap-operation-<uuid>`). The backend does not depend on it: the chain-write verifier\n * only requires a non-empty key of at most 256 characters, and apply-results accepts\n * `[A-Za-z0-9._:-]{1,128}`; the only code that mints a prefixed key itself is the server-side v1\n * trade builder, which nothing reads back by prefix.\n */\nexport const DEFAULT_UNIQUE_KEY_PREFIX = 'galaswap-operation-';\n\n/** Options shared by the services that mint `uniqueKey`s for writes. */\nexport interface UniqueKeyOptions {\n /**\n * Prefix of every minted `uniqueKey` (`<prefix><uuid>`). Defaults to\n * `DEFAULT_UNIQUE_KEY_PREFIX` (`galaswap-operation-`).\n */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/** A canonical UUID is 36 characters; the apply-results key limit is 128. */\nconst MAX_UNIQUE_KEY_PREFIX_LENGTH = 128 - 36;\nconst UNIQUE_KEY_PREFIX_PATTERN = /^[A-Za-z0-9._:-]*$/u;\n\n/**\n * Validates a caller-supplied `uniqueKey` prefix. The whole key (`<prefix><uuid>`) must stay a\n * valid apply-results key, otherwise `confirm()` could never read the outcome of the write.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY_PREFIX` when the prefix has characters outside\n * `A-Za-z0-9._:-` or is longer than 92 characters.\n */\nexport function resolveUniqueKeyPrefix(prefix: string | undefined): string {\n if (prefix === undefined) return DEFAULT_UNIQUE_KEY_PREFIX;\n if (!UNIQUE_KEY_PREFIX_PATTERN.test(prefix) || prefix.length > MAX_UNIQUE_KEY_PREFIX_LENGTH) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY_PREFIX', {\n uniqueKeyPrefix: prefix,\n maxLength: MAX_UNIQUE_KEY_PREFIX_LENGTH,\n });\n }\n return prefix;\n}\n\n/**\n * Validates a caller-supplied write `uniqueKey`: 1 to 128 characters of `A-Za-z0-9._:-`, the\n * shape the apply-results route accepts, so the write's outcome can always be read back with\n * `confirm()`. A key is one attempt's identity: reuse it only to retry that same attempt.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY` otherwise.\n */\nexport function assertUniqueKey(uniqueKey: string): void {\n if (!isValidUniqueKey(uniqueKey)) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY', { uniqueKey: String(uniqueKey) });\n }\n}\n\n/** The part of `globalThis.crypto` a uniqueKey needs: the one CSPRNG every target can offer. */\ninterface RandomValuesSource {\n getRandomValues?: ((array: Uint8Array) => unknown) | undefined;\n}\n\n/**\n * A random version-4 UUID (RFC 9562) in the canonical lowercase `8-4-4-4-12` form, byte for byte\n * the shape `crypto.randomUUID()` returns, built from `crypto.getRandomValues`. `randomUUID` is\n * NOT used: React Native's Hermes has no `crypto.randomUUID`, so a write would fail with\n * \"undefined is not a function\", while `getRandomValues` is what browsers, Node (>= 19 as a\n * global), MV3 service workers and Hermes with `react-native-get-random-values` all provide.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when there is no `getRandomValues`: a key minted from\n * `Math.random` could collide with another attempt's, so the SDK refuses rather than degrade.\n */\nfunction randomUuidV4(): string {\n const source = (globalThis as { crypto?: RandomValuesSource | undefined }).crypto;\n if (typeof source?.getRandomValues !== 'function') {\n throw new GalaSDKError('CSPRNG_UNAVAILABLE', {});\n }\n // Filled in place: a polyfill is not relied on to return the array.\n const bytes = new Uint8Array(16);\n source.getRandomValues(bytes);\n const hex: string[] = [];\n bytes.forEach((byte, index) => {\n // Version nibble 4 in byte 6, variant bits 10 in byte 8; everything else stays random.\n const value = index === 6 ? (byte & 0x0f) | 0x40 : index === 8 ? (byte & 0x3f) | 0x80 : byte;\n hex.push(value.toString(16).padStart(2, '0'));\n });\n const text = hex.join('');\n return [\n text.slice(0, 8),\n text.slice(8, 12),\n text.slice(12, 16),\n text.slice(16, 20),\n text.slice(20),\n ].join('-');\n}\n\n/**\n * A fresh per-attempt key: `<prefix><random UUID>`, the UUID a random version-4 one.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when the platform has no `crypto.getRandomValues`\n * (install a polyfill such as `react-native-get-random-values` on React Native).\n */\nexport function createUniqueKey(prefix: string): string {\n return `${prefix}${randomUuidV4()}`;\n}\n"],"mappings":"A,sHAUA,MAAaA,EAA4B,sBAanCC,EAA4B,sBASlC,SAAgBC,EAAuB,EAAoC,CACzE,GAAIC,IAAW,IAAA,GAAW,OAAOH,EACjC,GAAI,CAACC,EAA0B,KAAKE,CAAM,GAAKA,EAAO,OAAS,GAC7D,MAAM,IAAIC,EAAa,4BAA6B,CAClD,gBAAiBD,EACjB,UAAW,EACb,CAAC,EAEH,OAAOA,CACT,CASA,SAAgBE,EAAgB,EAAyB,CACvD,GAAI,CAACC,EAAiBC,CAAS,EAC7B,MAAM,IAAIH,EAAa,qBAAsB,CAAE,UAAW,OAAOG,CAAS,CAAE,CAAC,CAEjF,CAiBA,SAASC,GAAuB,CAC9B,IAAMC,EAAU,WAA2D,OAC3E,GAAI,OAAOA,GAAQ,iBAAoB,WACrC,MAAM,IAAIL,EAAa,qBAAsB,CAAC,CAAC,EAGjD,IAAMM,kBAAQ,IAAI,WAAW,EAAE,EAC/BD,EAAO,gBAAgBC,CAAK,EAC5B,IAAMC,EAAgB,CAAC,EACvBD,EAAM,SAAS,EAAM,IAAU,CAE7B,IAAME,EAAQC,IAAU,EAAKC,EAAO,GAAQ,GAAOD,IAAU,EAAKC,EAAO,GAAQ,IAAOA,EACxFH,EAAI,KAAKC,EAAM,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAC9C,CAAC,EACD,IAAMG,EAAOJ,EAAI,KAAK,EAAE,EACxB,MAAO,CACLI,EAAK,MAAM,EAAG,CAAC,EACfA,EAAK,MAAM,EAAG,EAAE,EAChBA,EAAK,MAAM,GAAI,EAAE,EACjBA,EAAK,MAAM,GAAI,EAAE,EACjBA,EAAK,MAAM,EAAE,CACf,CAAC,CAAC,KAAK,GAAG,CACZ,CAQA,SAAgBC,EAAgB,EAAwB,CACtD,MAAO,GAAGb,IAASK,EAAa,GAClC,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"unique_key_syntax.js","names":["UNIQUE_KEY_PATTERN","isValidUniqueKey","uniqueKey"],"sources":["../../../src/utils/unique_key_syntax.ts"],"sourcesContent":["/**\n * The shape of a write `uniqueKey`, with NO imports: the pending-swap store and the failure guards\n * need only this check, and importing it from `unique_key.ts` would drag in `GalaSDKError` and the\n * whole error catalog for it.\n */\n\n/** The swap backend's apply-results key constraint (`apply-results.dto.ts`). */\nconst UNIQUE_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;\n\n/**\n * True when `uniqueKey` is a usable write key: 1 to 128 characters of `A-Za-z0-9._:-`, the shape\n * the apply-results route accepts. The one definition behind `assertUniqueKey`, `confirm()` and\n * the pending-swap store, so they can never disagree about what a valid key is.\n */\nexport function isValidUniqueKey(uniqueKey: unknown): uniqueKey is string {\n return typeof uniqueKey === 'string' && UNIQUE_KEY_PATTERN.test(uniqueKey);\n}\n"],"mappings":"AAOA,MAAMA,EAAqB,4BAO3B,SAAgBC,EAAiB,EAAyC,CACxE,OAAO,OAAOC,GAAc,UAAYF,EAAmB,KAAKE,CAAS,CAC3E"}
1
+ {"version":3,"file":"unique_key_syntax.js","names":["UNIQUE_KEY_PATTERN","isValidUniqueKey","uniqueKey"],"sources":["../../../src/utils/unique_key_syntax.ts"],"sourcesContent":["/**\n * The shape of a write `uniqueKey`, with NO imports: the pending-swap store and the failure guards\n * need only this check, and importing it from `unique_key.ts` would drag in `GalaSDKError` and the\n * whole error catalog for it.\n */\n\n/** The swap backend's apply-results key constraint (`apply-results.dto.ts`). */\nconst UNIQUE_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;\n\n/**\n * True when `uniqueKey` is a usable write key: 1 to 128 characters of `A-Za-z0-9._:-`, the shape\n * the apply-results route accepts. The one definition behind `assertUniqueKey`, `confirm()` and\n * the pending-swap store, so they can never disagree about what a valid key is.\n */\nexport function isValidUniqueKey(uniqueKey: unknown): uniqueKey is string {\n return typeof uniqueKey === 'string' && UNIQUE_KEY_PATTERN.test(uniqueKey);\n}\n"],"mappings":"AAOA,MAAMA,EAAqB,4BAO3B,SAAgBC,EAAiB,EAAyC,CACxE,OAAO,OAAOC,GAAc,UAAYF,EAAmB,KAAKE,CAAS,CAC3E,C"}