@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":"wallet_keys.js","names":["KEY_DIGITS","PREFIXED_KEY","MNEMONIC_WORD","mnemonicWords","words","text","word","walletOfKey","address","checksumEthereumAddress","ethAddressOfPrivateKey","key","bytesToHex","walletOfMnemonic","wordlist","GalaSDKError","phrase","validateMnemonic","seed","mnemonicToSeedSync","node","HDKey","normalizePrivateKey","given","randomEntropy","source","entropy","createWallet","input","mnemonic","entropyToMnemonic","validateWalletInput","prefixedKey","privateKey","getPublicKeyFromPrivateKey","secp256k1","getEthereumAddressFromPrivateKey"],"sources":["../../../src/utils/wallet_keys.ts"],"sourcesContent":["/**\n * Ethereum wallets from nothing (random), a private key or a BIP-39 mnemonic, and the public data\n * of a key: moved from launchpad-sdk's `helpers/wallet.ts` (which used ethers) and replayed against\n * its recorded vectors (tests/wallet_keys.test.ts, tests/fixtures/wallet-helpers-recorded.json).\n *\n * - A mnemonic derives the key ethers did: the BIP-39 seed of the phrase (English wordlist, no\n * passphrase) at `m/44'/60'/0'/0/0`. The phrase is read case-insensitively and with any\n * whitespace between its words, as ethers did; the derivation always uses the canonical phrase\n * (lower case, single spaces), so the same words always give the same key.\n * - A random wallet is 128 bits from `crypto.getRandomValues` as a 12-word mnemonic (ethers'\n * `Wallet.createRandom`). Without a CSPRNG it is `CSPRNG_UNAVAILABLE`, never a weaker source.\n * - Every refusal is a `GalaSDKError` naming no part of the input (it may be a secret).\n */\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { bytesToHex } from '@noble/hashes/utils';\nimport { HDKey } from '@scure/bip32';\nimport { entropyToMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { checksumEthereumAddress } from './eth_address.js';\nimport { ethAddressOfPrivateKey, normalizePrivateKey } from './signing.js';\n\n/** A wallet: its key, its account in both spellings, and the mnemonic it came from. */\nexport interface GeneratedWallet {\n /** `0x` plus 64 lower-case hex digits. */\n readonly privateKey: string;\n /** `0x` plus the EIP-55 checksummed digits. */\n readonly address: string;\n /** `eth|` plus the checksummed digits: the GalaChain spelling of `address`. */\n readonly galaAddress: string;\n /** The mnemonic as it was given (generated: 12 words), or `''` for a wallet made from a key. */\n readonly mnemonic: string;\n}\n\n/** What {@link validateWalletInput} found. */\nexport type WalletInputValidation =\n | { readonly valid: true; readonly format: 'private_key' | 'mnemonic' }\n | { readonly valid: false; readonly error: string };\n\n/** The two encodings of a secp256k1 public key. */\nexport interface PublicKeyResult {\n /** Uncompressed: `0x04` plus x and y (132 characters). */\n readonly publicKey: string;\n /** Compressed: `0x02` / `0x03` plus x (68 characters). */\n readonly compressedPublicKey: string;\n}\n\n/** The account path ethers (and MetaMask) use for the first account of a mnemonic. */\nconst FIRST_ACCOUNT_PATH = \"m/44'/60'/0'/0/0\";\n\nconst KEY_DIGITS = /^(?:0x)?[0-9a-fA-F]{64}$/u;\nconst PREFIXED_KEY = /^0x[0-9a-fA-F]{64}$/u;\nconst MNEMONIC_WORD = /^[a-zA-Z]+$/u;\n\n/** The words of a 12- or 24-word phrase of letters, or `undefined` when it is not one. */\nfunction mnemonicWords(text: string): string[] | undefined {\n const words = text.split(/\\s+/u).filter((word) => word.length > 0);\n if (words.length !== 12 && words.length !== 24) return undefined;\n return words.every((word) => MNEMONIC_WORD.test(word)) ? words : undefined;\n}\n\nfunction walletOfKey(key: Uint8Array, mnemonic: string): GeneratedWallet {\n try {\n const address = checksumEthereumAddress(ethAddressOfPrivateKey(key)) as string;\n return {\n privateKey: `0x${bytesToHex(key)}`,\n address,\n galaAddress: `eth|${address.slice(2)}`,\n mnemonic,\n };\n } finally {\n key.fill(0);\n }\n}\n\n/** The first account of a mnemonic, given as its (lower-case) words. */\nfunction walletOfMnemonic(words: readonly string[], given: string): GeneratedWallet {\n if (!words.every((word) => wordlist.includes(word))) {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'unknown_mnemonic_word' });\n }\n const phrase = words.join(' ');\n if (!validateMnemonic(phrase, wordlist)) {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'mnemonic_checksum' });\n }\n const seed = mnemonicToSeedSync(phrase);\n const node = HDKey.fromMasterSeed(seed).derive(FIRST_ACCOUNT_PATH);\n seed.fill(0);\n try {\n // A node derived from a seed always holds its key; were it ever null, normalizePrivateKey\n // refuses it (INVALID_PRIVATE_KEY), it is never used. The key is copied, then wiped below.\n return walletOfKey(normalizePrivateKey(node.privateKey as Uint8Array), given);\n } finally {\n node.wipePrivateData();\n }\n}\n\n/** 16 bytes from `crypto.getRandomValues`, or `CSPRNG_UNAVAILABLE`. */\nfunction randomEntropy(): Uint8Array {\n const source = (\n globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => unknown } | undefined }\n ).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 entropy = new Uint8Array(16);\n source.getRandomValues(entropy);\n return entropy;\n}\n\n/**\n * A wallet: a new random one (no input), or the one a private key or a mnemonic names.\n *\n * - no input: a new 12-word mnemonic and its first account;\n * - 64 hex digits (with or without `0x`, any case): that key;\n * - 12 or 24 words: the mnemonic's first account (`m/44'/60'/0'/0/0`), read case-insensitively.\n *\n * Use the key with any signer: `new PrivateKeySigner(wallet.privateKey)`,\n * `new PrivateKeyProvider(wallet.privateKey)`, or an ethers `new Wallet(wallet.privateKey)`.\n *\n * @throws GalaSDKError `INVALID_WALLET_INPUT` (`empty`, `unrecognized_format`,\n * `unknown_mnemonic_word`, `mnemonic_checksum`), `INVALID_PRIVATE_KEY` (`not_on_curve`: zero or not\n * below the curve order), `CSPRNG_UNAVAILABLE` (a random wallet with no `crypto.getRandomValues`).\n *\n * @example\n * ```typescript\n * const fresh = createWallet();\n * const restored = createWallet(fresh.mnemonic);\n * restored.privateKey === fresh.privateKey; // true\n * ```\n */\nexport function createWallet(input?: string): GeneratedWallet {\n if (input === undefined) {\n const entropy = randomEntropy();\n const mnemonic = entropyToMnemonic(entropy, wordlist);\n entropy.fill(0);\n return walletOfMnemonic(mnemonic.split(' '), mnemonic);\n }\n if (typeof input !== 'string') {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'unrecognized_format' });\n }\n const given = input.trim();\n if (given === '') {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'empty' });\n }\n if (KEY_DIGITS.test(given)) {\n return walletOfKey(normalizePrivateKey(given), '');\n }\n const words = mnemonicWords(given);\n if (words === undefined) {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'unrecognized_format' });\n }\n return walletOfMnemonic(\n words.map((word) => word.toLowerCase()),\n given,\n );\n}\n\n/**\n * Which kind of wallet input `input` is, without deriving anything: a private key (64 hex digits,\n * `0x` optional) or a mnemonic (12 or 24 words of letters). It checks the FORM only: a mnemonic\n * with an unknown word or a wrong checksum is still `mnemonic` here (`createWallet` refuses it).\n *\n * @example\n * ```typescript\n * validateWalletInput('0x' + '11'.repeat(32)); // { valid: true, format: 'private_key' }\n * ```\n */\nexport function validateWalletInput(input: string): WalletInputValidation {\n const given = typeof input === 'string' ? input.trim() : '';\n if (given === '') return { valid: false, error: 'Input cannot be empty string' };\n if (KEY_DIGITS.test(given)) return { valid: true, format: 'private_key' };\n if (mnemonicWords(given) !== undefined) return { valid: true, format: 'mnemonic' };\n return {\n valid: false,\n error:\n 'Unable to detect input format. Expected private key (64 hex chars) or mnemonic (12/24 words)',\n };\n}\n\n/** The key of a `0x`-prefixed 64-hex-digit string (the form these two helpers take). */\nfunction prefixedKey(privateKey: string): Uint8Array {\n if (typeof privateKey !== 'string' || !PREFIXED_KEY.test(privateKey)) {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n return normalizePrivateKey(privateKey);\n}\n\n/**\n * The secp256k1 public key of a private key, uncompressed and compressed.\n *\n * @param privateKey `0x` plus 64 hex digits.\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` (`bad_encoding`, `not_on_curve`).\n *\n * @example\n * ```typescript\n * const { publicKey, compressedPublicKey } = getPublicKeyFromPrivateKey(key); // '0x04...', '0x02...'\n * ```\n */\nexport function getPublicKeyFromPrivateKey(privateKey: string): PublicKeyResult {\n const key = prefixedKey(privateKey);\n try {\n return {\n publicKey: `0x${bytesToHex(secp256k1.getPublicKey(key, false))}`,\n compressedPublicKey: `0x${bytesToHex(secp256k1.getPublicKey(key, true))}`,\n };\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * The Ethereum account of a private key: `0x` plus the EIP-55 checksummed digits (for the\n * GalaChain spelling, `eth|` plus the same digits).\n *\n * @param privateKey `0x` plus 64 hex digits.\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` (`bad_encoding`, `not_on_curve`).\n *\n * @example\n * ```typescript\n * getEthereumAddressFromPrivateKey(key); // '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'\n * ```\n */\nexport function getEthereumAddressFromPrivateKey(privateKey: string): string {\n const key = prefixedKey(privateKey);\n try {\n return checksumEthereumAddress(ethAddressOfPrivateKey(key)) as string;\n } finally {\n key.fill(0);\n }\n}\n"],"mappings":"yeAgDA,MAEMA,EAAa,4BACbC,EAAe,uBACfC,EAAgB,eAGtB,SAASC,EAAc,EAAoC,CACzD,IAAMC,EAAQC,EAAK,MAAM,MAAM,CAAC,CAAC,OAAQ,GAASC,EAAK,OAAS,CAAC,EACjE,GAAIF,EAAM,SAAW,IAAMA,EAAM,SAAW,GAC5C,OAAOA,EAAM,MAAO,GAASF,EAAc,KAAKI,CAAI,CAAC,EAAIF,EAAQ,IAAA,EACnE,CAEA,SAASG,EAAY,EAAiB,EAAmC,CACvE,GAAI,CACF,IAAMC,EAAUC,EAAwBC,EAAuBC,CAAG,CAAC,EACnE,MAAO,CACL,WAAY,KAAKC,EAAWD,CAAG,IAC/B,UACA,YAAa,OAAOH,EAAQ,MAAM,CAAC,IACnC,UACF,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","PREFIXED_KEY","MNEMONIC_WORD","mnemonicWords","words","text","word","walletOfKey","address","checksumEthereumAddress","ethAddressOfPrivateKey","key","bytesToHex","walletOfMnemonic","wordlist","GalaSDKError","phrase","validateMnemonic","seed","mnemonicToSeedSync","node","HDKey","normalizePrivateKey","given","randomEntropy","source","entropy","createWallet","input","mnemonic","entropyToMnemonic","validateWalletInput","prefixedKey","privateKey","getPublicKeyFromPrivateKey","secp256k1","getEthereumAddressFromPrivateKey"],"sources":["../../../src/utils/wallet_keys.ts"],"sourcesContent":["/**\n * Ethereum wallets from nothing (random), a private key or a BIP-39 mnemonic, and the public data\n * of a key: moved from launchpad-sdk's `helpers/wallet.ts` (which used ethers) and replayed against\n * its recorded vectors (tests/wallet_keys.test.ts, tests/fixtures/wallet-helpers-recorded.json).\n *\n * - A mnemonic derives the key ethers did: the BIP-39 seed of the phrase (English wordlist, no\n * passphrase) at `m/44'/60'/0'/0/0`. The phrase is read case-insensitively and with any\n * whitespace between its words, as ethers did; the derivation always uses the canonical phrase\n * (lower case, single spaces), so the same words always give the same key.\n * - A random wallet is 128 bits from `crypto.getRandomValues` as a 12-word mnemonic (ethers'\n * `Wallet.createRandom`). Without a CSPRNG it is `CSPRNG_UNAVAILABLE`, never a weaker source.\n * - Every refusal is a `GalaSDKError` naming no part of the input (it may be a secret).\n */\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { bytesToHex } from '@noble/hashes/utils';\nimport { HDKey } from '@scure/bip32';\nimport { entropyToMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { checksumEthereumAddress } from './eth_address.js';\nimport { ethAddressOfPrivateKey, normalizePrivateKey } from './signing.js';\n\n/** A wallet: its key, its account in both spellings, and the mnemonic it came from. */\nexport interface GeneratedWallet {\n /** `0x` plus 64 lower-case hex digits. */\n readonly privateKey: string;\n /** `0x` plus the EIP-55 checksummed digits. */\n readonly address: string;\n /** `eth|` plus the checksummed digits: the GalaChain spelling of `address`. */\n readonly galaAddress: string;\n /** The mnemonic as it was given (generated: 12 words), or `''` for a wallet made from a key. */\n readonly mnemonic: string;\n}\n\n/** What {@link validateWalletInput} found. */\nexport type WalletInputValidation =\n | { readonly valid: true; readonly format: 'private_key' | 'mnemonic' }\n | { readonly valid: false; readonly error: string };\n\n/** The two encodings of a secp256k1 public key. */\nexport interface PublicKeyResult {\n /** Uncompressed: `0x04` plus x and y (132 characters). */\n readonly publicKey: string;\n /** Compressed: `0x02` / `0x03` plus x (68 characters). */\n readonly compressedPublicKey: string;\n}\n\n/** The account path ethers (and MetaMask) use for the first account of a mnemonic. */\nconst FIRST_ACCOUNT_PATH = \"m/44'/60'/0'/0/0\";\n\nconst KEY_DIGITS = /^(?:0x)?[0-9a-fA-F]{64}$/u;\nconst PREFIXED_KEY = /^0x[0-9a-fA-F]{64}$/u;\nconst MNEMONIC_WORD = /^[a-zA-Z]+$/u;\n\n/** The words of a 12- or 24-word phrase of letters, or `undefined` when it is not one. */\nfunction mnemonicWords(text: string): string[] | undefined {\n const words = text.split(/\\s+/u).filter((word) => word.length > 0);\n if (words.length !== 12 && words.length !== 24) return undefined;\n return words.every((word) => MNEMONIC_WORD.test(word)) ? words : undefined;\n}\n\nfunction walletOfKey(key: Uint8Array, mnemonic: string): GeneratedWallet {\n try {\n const address = checksumEthereumAddress(ethAddressOfPrivateKey(key)) as string;\n return {\n privateKey: `0x${bytesToHex(key)}`,\n address,\n galaAddress: `eth|${address.slice(2)}`,\n mnemonic,\n };\n } finally {\n key.fill(0);\n }\n}\n\n/** The first account of a mnemonic, given as its (lower-case) words. */\nfunction walletOfMnemonic(words: readonly string[], given: string): GeneratedWallet {\n if (!words.every((word) => wordlist.includes(word))) {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'unknown_mnemonic_word' });\n }\n const phrase = words.join(' ');\n if (!validateMnemonic(phrase, wordlist)) {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'mnemonic_checksum' });\n }\n const seed = mnemonicToSeedSync(phrase);\n const node = HDKey.fromMasterSeed(seed).derive(FIRST_ACCOUNT_PATH);\n seed.fill(0);\n try {\n // A node derived from a seed always holds its key; were it ever null, normalizePrivateKey\n // refuses it (INVALID_PRIVATE_KEY), it is never used. The key is copied, then wiped below.\n return walletOfKey(normalizePrivateKey(node.privateKey as Uint8Array), given);\n } finally {\n node.wipePrivateData();\n }\n}\n\n/** 16 bytes from `crypto.getRandomValues`, or `CSPRNG_UNAVAILABLE`. */\nfunction randomEntropy(): Uint8Array {\n const source = (\n globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => unknown } | undefined }\n ).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 entropy = new Uint8Array(16);\n source.getRandomValues(entropy);\n return entropy;\n}\n\n/**\n * A wallet: a new random one (no input), or the one a private key or a mnemonic names.\n *\n * - no input: a new 12-word mnemonic and its first account;\n * - 64 hex digits (with or without `0x`, any case): that key;\n * - 12 or 24 words: the mnemonic's first account (`m/44'/60'/0'/0/0`), read case-insensitively.\n *\n * Use the key with any signer: `new PrivateKeySigner(wallet.privateKey)`,\n * `new PrivateKeyProvider(wallet.privateKey)`, or an ethers `new Wallet(wallet.privateKey)`.\n *\n * @throws GalaSDKError `INVALID_WALLET_INPUT` (`empty`, `unrecognized_format`,\n * `unknown_mnemonic_word`, `mnemonic_checksum`), `INVALID_PRIVATE_KEY` (`not_on_curve`: zero or not\n * below the curve order), `CSPRNG_UNAVAILABLE` (a random wallet with no `crypto.getRandomValues`).\n *\n * @example\n * ```typescript\n * const fresh = createWallet();\n * const restored = createWallet(fresh.mnemonic);\n * restored.privateKey === fresh.privateKey; // true\n * ```\n */\nexport function createWallet(input?: string): GeneratedWallet {\n if (input === undefined) {\n const entropy = randomEntropy();\n const mnemonic = entropyToMnemonic(entropy, wordlist);\n entropy.fill(0);\n return walletOfMnemonic(mnemonic.split(' '), mnemonic);\n }\n if (typeof input !== 'string') {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'unrecognized_format' });\n }\n const given = input.trim();\n if (given === '') {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'empty' });\n }\n if (KEY_DIGITS.test(given)) {\n return walletOfKey(normalizePrivateKey(given), '');\n }\n const words = mnemonicWords(given);\n if (words === undefined) {\n throw new GalaSDKError('INVALID_WALLET_INPUT', { reason: 'unrecognized_format' });\n }\n return walletOfMnemonic(\n words.map((word) => word.toLowerCase()),\n given,\n );\n}\n\n/**\n * Which kind of wallet input `input` is, without deriving anything: a private key (64 hex digits,\n * `0x` optional) or a mnemonic (12 or 24 words of letters). It checks the FORM only: a mnemonic\n * with an unknown word or a wrong checksum is still `mnemonic` here (`createWallet` refuses it).\n *\n * @example\n * ```typescript\n * validateWalletInput('0x' + '11'.repeat(32)); // { valid: true, format: 'private_key' }\n * ```\n */\nexport function validateWalletInput(input: string): WalletInputValidation {\n const given = typeof input === 'string' ? input.trim() : '';\n if (given === '') return { valid: false, error: 'Input cannot be empty string' };\n if (KEY_DIGITS.test(given)) return { valid: true, format: 'private_key' };\n if (mnemonicWords(given) !== undefined) return { valid: true, format: 'mnemonic' };\n return {\n valid: false,\n error:\n 'Unable to detect input format. Expected private key (64 hex chars) or mnemonic (12/24 words)',\n };\n}\n\n/** The key of a `0x`-prefixed 64-hex-digit string (the form these two helpers take). */\nfunction prefixedKey(privateKey: string): Uint8Array {\n if (typeof privateKey !== 'string' || !PREFIXED_KEY.test(privateKey)) {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n return normalizePrivateKey(privateKey);\n}\n\n/**\n * The secp256k1 public key of a private key, uncompressed and compressed.\n *\n * @param privateKey `0x` plus 64 hex digits.\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` (`bad_encoding`, `not_on_curve`).\n *\n * @example\n * ```typescript\n * const { publicKey, compressedPublicKey } = getPublicKeyFromPrivateKey(key); // '0x04...', '0x02...'\n * ```\n */\nexport function getPublicKeyFromPrivateKey(privateKey: string): PublicKeyResult {\n const key = prefixedKey(privateKey);\n try {\n return {\n publicKey: `0x${bytesToHex(secp256k1.getPublicKey(key, false))}`,\n compressedPublicKey: `0x${bytesToHex(secp256k1.getPublicKey(key, true))}`,\n };\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * The Ethereum account of a private key: `0x` plus the EIP-55 checksummed digits (for the\n * GalaChain spelling, `eth|` plus the same digits).\n *\n * @param privateKey `0x` plus 64 hex digits.\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` (`bad_encoding`, `not_on_curve`).\n *\n * @example\n * ```typescript\n * getEthereumAddressFromPrivateKey(key); // '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'\n * ```\n */\nexport function getEthereumAddressFromPrivateKey(privateKey: string): string {\n const key = prefixedKey(privateKey);\n try {\n return checksumEthereumAddress(ethAddressOfPrivateKey(key)) as string;\n } finally {\n key.fill(0);\n }\n}\n"],"mappings":"A,yeAgDA,MAEMA,EAAa,4BACbC,EAAe,uBACfC,EAAgB,eAGtB,SAASC,EAAc,EAAoC,CACzD,IAAMC,EAAQC,EAAK,MAAM,MAAM,CAAC,CAAC,OAAQ,GAASC,EAAK,OAAS,CAAC,EACjE,GAAIF,EAAM,SAAW,IAAMA,EAAM,SAAW,GAC5C,OAAOA,EAAM,MAAO,GAASF,EAAc,KAAKI,CAAI,CAAC,EAAIF,EAAQ,IAAA,EACnE,CAEA,SAASG,EAAY,EAAiB,EAAmC,CACvE,GAAI,CACF,IAAMC,EAAUC,EAAwBC,EAAuBC,CAAG,CAAC,EACnE,MAAO,CACL,WAAY,KAAKC,EAAWD,CAAG,IAC/B,UACA,YAAa,OAAOH,EAAQ,MAAM,CAAC,IACnC,UACF,CACF,QAAU,CACRG,EAAI,KAAK,CAAC,CACZ,CACF,CAGA,SAASE,EAAiB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","wordsADecline","lower","text","phrase","isWalletUserRejection","isGalaErrorLike","\"reason\"","hasGalaErrorBrand","\"code\"","\"name\"","walletDeclineCode","code"],"sources":["../../../src/utils/wallet_rejection.ts"],"sourcesContent":["/**\n * What the SDK knows about a failure thrown by a WALLET (the signer an app supplies, or wallet\n * code of the app's own): the code the wallet put on it, and whether it means the person declined.\n * Both read only the wallet's own error value; neither shows or forwards its text.\n */\n\nimport { hasGalaErrorBrand, isGalaErrorLike } from './error_brand.js';\n\n// This module is the whole of the light `@gala-chain/gala-core-sdk/wallet` entry (and the main\n// entry re-exports it, so there is one implementation). It must stay dependency-free: it may\n// import only `./error_brand.js`, never the error catalog, `GalaSDKError` or the main index.\n\n/** Codes the EIP-1193 / ethers / viem families use for \"the person declined in the wallet\". */\nconst REJECTION_CODES: readonly unknown[] = [4001, 'ACTION_REJECTED', 'USER_REJECTED'];\n\n/** The `name` viem / wagmi give the error of a declined request. */\nconst REJECTION_NAME = 'UserRejectedRequestError';\n\n/**\n * Wordings of a decline, matched case-insensitively as substrings. This is a LAST RESORT for\n * wallets that set neither a `code` nor a `name`: it reads a third party's text, so it is broad on\n * purpose (a superset of the matchers the Gala wallet and gSwap web app used) and can in principle\n * match an unrelated message that uses these words.\n */\nconst REJECTION_PHRASES: readonly string[] = [\n 'user rejected',\n 'user denied',\n 'user cancel',\n 'rejected the request',\n 'request rejected',\n 'rejected by user',\n 'action_rejected',\n 'cancelled',\n 'canceled',\n];\n\n/** Properties wallets nest their text under (EIP-1193, ethers, viem, Gala wallet). */\nconst TEXT_KEYS: readonly string[] = [\n 'message',\n 'Message',\n 'shortMessage',\n 'details',\n 'errorDetails',\n 'reason',\n];\n\n/** Wallet errors nest their text at most a level or two deep; the bound also stops a cyclic object. */\nconst MAX_TEXT_DEPTH = 3;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction textsOf(value: unknown, depth = 0): string[] {\n if (typeof value === 'string') return [value];\n if (!isRecord(value) || depth >= MAX_TEXT_DEPTH) return [];\n return TEXT_KEYS.flatMap((key) => textsOf(value[key], depth + 1));\n}\n\nfunction wordsADecline(text: string): boolean {\n const lower = text.toLowerCase();\n return (\n REJECTION_PHRASES.some((phrase) => lower.includes(phrase)) ||\n (lower.includes('signature') && lower.includes('cancel'))\n );\n}\n\n/**\n * True when a wallet's error (or just its message text) says the person DECLINED the request in\n * their wallet. This is exactly the test behind `SIGNING_FAILED` with `params.reason ===\n * 'user_rejected'`, exported for wallet code outside the SDK (connect and registration flows, a\n * v1 write path) so an app keeps no matcher of its own.\n *\n * It is decided from the wallet's own fields first: a `code` of `4001` (EIP-1193), `'ACTION_REJECTED'`\n * (ethers) or `'USER_REJECTED'`, or `name === 'UserRejectedRequestError'` (viem). Only when those are\n * absent is the wallet's TEXT read (`message`, `Message`, `shortMessage`, `details`, `errorDetails`,\n * `reason`, up to three levels deep, or a bare string): \"user rejected\", \"user denied\", \"user\n * cancelled\", \"request rejected\", \"rejected by user\", \"rejected the request\", \"cancelled\" /\n * \"canceled\", or a \"signature ... cancel\" sentence. The wording fallback is a last resort for\n * wallets that do not set codes; prefer `code` and `name` wherever you control the wallet.\n *\n * An SDK error is never read by its text: a `SIGNING_FAILED` is a decline exactly when its\n * `params.reason` is `user_rejected`, and every other SDK error is not one. The same holds for a\n * plain-object VIEW of an SDK error (`{ code: 'SIGNING_FAILED', params: { reason } }`, the shape\n * of an app's wrapper): a string `code` plus an object `params` is decided by the code alone, with\n * the wallet code list above still honoured for a view that is not branded, and its English is\n * never read. This works without `instanceof`, so it is safe across two copies of the SDK.\n *\n * @example\n * ```ts\n * try {\n * await wallet.connect();\n * } catch (error) {\n * if (isWalletUserRejection(error)) return; // the person said no: not an error to report\n * report(error);\n * }\n * ```\n */\nexport function isWalletUserRejection(value: unknown): boolean {\n if (isGalaErrorLike(value)) {\n if (value.code === 'SIGNING_FAILED') return value.params['reason'] === 'user_rejected';\n return !hasGalaErrorBrand(value) && REJECTION_CODES.includes(value.code);\n }\n if (isRecord(value)) {\n if (REJECTION_CODES.includes(value['code']) || value['name'] === REJECTION_NAME) return true;\n }\n return textsOf(value).some(wordsADecline);\n}\n\n/** The longest wallet code kept: real ones (`4001`, `ACTION_REJECTED`) are short. */\nconst MAX_WALLET_CODE_LENGTH = 64;\n\n/**\n * The code a wallet put on its error: an EIP-1193 / JSON-RPC number (`4001`, `-32603`) or an\n * ethers / viem string (`'ACTION_REJECTED'`), read from the error's own top-level `code`. Anything\n * else (no code, a non-finite number, an empty or very long string, an object) is `undefined`, so\n * the value is always a safe primitive. Used for `GalaSDKError.walletCode`.\n *\n * @example\n * ```ts\n * walletDeclineCode({ code: 4001, message: 'User rejected the request.' }); // 4001\n * walletDeclineCode(new Error('locked')); // undefined\n * ```\n */\nexport function walletDeclineCode(value: unknown): number | string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { code } = value as { code?: unknown };\n if (typeof code === 'number') return Number.isFinite(code) ? code : undefined;\n if (typeof code === 'string' && code.length > 0 && code.length <= MAX_WALLET_CODE_LENGTH) {\n return code;\n }\n return undefined;\n}\n"],"mappings":"0EAaA,MAAMA,EAAsC,CAAC,KAAM,kBAAmB,eAAe,EAW/EC,EAAuC,CAC3C,gBACA,cACA,cACA,uBACA,mBACA,mBACA,kBACA,YACA,UACF,EAGMC,EAA+B,CACnC,UACA,UACA,eACA,UACA,eACA,QACF,EAKA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAEA,SAASC,EAAQ,EAAgB,EAAQ,EAAa,CAGpD,OAFI,OAAOD,GAAU,SAAiB,CAACA,CAAK,EACxC,CAACD,EAASC,CAAK,GAAKE,GAAS,EAAuB,CAAC,EAClDJ,EAAU,QAAS,GAAQG,EAAQD,EAAMG,GAAMD,EAAQ,CAAC,CAAC,CAClE,CAEA,SAASE,EAAc,EAAuB,CAC5C,IAAMC,EAAQC,EAAK,YAAY,EAC/B,OACET,EAAkB,KAAM,GAAWQ,EAAM,SAASE,CAAM,CAAC,GACxDF,EAAM,SAAS,WAAW,GAAKA,EAAM,SAAS,QAAQ,CAE3D,CAiCA,SAAgBG,EAAsB,EAAyB,CAQ7D,OAPIC,EAAgBT,CAAK,EACnBA,EAAM,OAAS,iBAAyBA,EAAM,OAAOU,SAAc,gBAChE,CAACC,EAAkBX,CAAK,GAAKJ,EAAgB,SAASI,EAAM,IAAI,EAErED,EAASC,CAAK,IACZJ,EAAgB,SAASI,EAAMY,IAAO,GAAKZ,EAAMa,OAAY,4BAAuB,GAEnFZ,EAAQD,CAAK,CAAC,CAAC,KAAKI,CAAa,CAC1C,CAiBA,SAAgBU,EAAkB,EAA6C,CAC7E,GAAI,OAAOd,GAAU,WAAYA,EAAgB,OACjD,GAAM,CAAE,QAASA,EACjB,GAAI,OAAOe,GAAS,SAAU,OAAO,OAAO,SAASA,CAAI,EAAIA,EAAO,IAAA,GACpE,GAAI,OAAOA,GAAS,UAAYA,EAAK,OAAS,GAAKA,EAAK,QAAU,GAChE,OAAOA,CAGX"}
1
+ {"version":3,"file":"wallet_rejection.js","names":["REJECTION_CODES","REJECTION_PHRASES","TEXT_KEYS","isRecord","value","textsOf","depth","key","wordsADecline","lower","text","phrase","isWalletUserRejection","isGalaErrorLike","\"reason\"","hasGalaErrorBrand","\"code\"","\"name\"","walletDeclineCode","code"],"sources":["../../../src/utils/wallet_rejection.ts"],"sourcesContent":["/**\n * What the SDK knows about a failure thrown by a WALLET (the signer an app supplies, or wallet\n * code of the app's own): the code the wallet put on it, and whether it means the person declined.\n * Both read only the wallet's own error value; neither shows or forwards its text.\n */\n\nimport { hasGalaErrorBrand, isGalaErrorLike } from './error_brand.js';\n\n// This module is the whole of the light `@gala-chain/gala-core-sdk/wallet` entry (and the main\n// entry re-exports it, so there is one implementation). It must stay dependency-free: it may\n// import only `./error_brand.js`, never the error catalog, `GalaSDKError` or the main index.\n\n/** Codes the EIP-1193 / ethers / viem families use for \"the person declined in the wallet\". */\nconst REJECTION_CODES: readonly unknown[] = [4001, 'ACTION_REJECTED', 'USER_REJECTED'];\n\n/** The `name` viem / wagmi give the error of a declined request. */\nconst REJECTION_NAME = 'UserRejectedRequestError';\n\n/**\n * Wordings of a decline, matched case-insensitively as substrings. This is a LAST RESORT for\n * wallets that set neither a `code` nor a `name`: it reads a third party's text, so it is broad on\n * purpose (a superset of the matchers the Gala wallet and gSwap web app used) and can in principle\n * match an unrelated message that uses these words.\n */\nconst REJECTION_PHRASES: readonly string[] = [\n 'user rejected',\n 'user denied',\n 'user cancel',\n 'rejected the request',\n 'request rejected',\n 'rejected by user',\n 'action_rejected',\n 'cancelled',\n 'canceled',\n];\n\n/** Properties wallets nest their text under (EIP-1193, ethers, viem, Gala wallet). */\nconst TEXT_KEYS: readonly string[] = [\n 'message',\n 'Message',\n 'shortMessage',\n 'details',\n 'errorDetails',\n 'reason',\n];\n\n/** Wallet errors nest their text at most a level or two deep; the bound also stops a cyclic object. */\nconst MAX_TEXT_DEPTH = 3;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction textsOf(value: unknown, depth = 0): string[] {\n if (typeof value === 'string') return [value];\n if (!isRecord(value) || depth >= MAX_TEXT_DEPTH) return [];\n return TEXT_KEYS.flatMap((key) => textsOf(value[key], depth + 1));\n}\n\nfunction wordsADecline(text: string): boolean {\n const lower = text.toLowerCase();\n return (\n REJECTION_PHRASES.some((phrase) => lower.includes(phrase)) ||\n (lower.includes('signature') && lower.includes('cancel'))\n );\n}\n\n/**\n * True when a wallet's error (or just its message text) says the person DECLINED the request in\n * their wallet. This is exactly the test behind `SIGNING_FAILED` with `params.reason ===\n * 'user_rejected'`, exported for wallet code outside the SDK (connect and registration flows, a\n * v1 write path) so an app keeps no matcher of its own.\n *\n * It is decided from the wallet's own fields first: a `code` of `4001` (EIP-1193), `'ACTION_REJECTED'`\n * (ethers) or `'USER_REJECTED'`, or `name === 'UserRejectedRequestError'` (viem). Only when those are\n * absent is the wallet's TEXT read (`message`, `Message`, `shortMessage`, `details`, `errorDetails`,\n * `reason`, up to three levels deep, or a bare string): \"user rejected\", \"user denied\", \"user\n * cancelled\", \"request rejected\", \"rejected by user\", \"rejected the request\", \"cancelled\" /\n * \"canceled\", or a \"signature ... cancel\" sentence. The wording fallback is a last resort for\n * wallets that do not set codes; prefer `code` and `name` wherever you control the wallet.\n *\n * An SDK error is never read by its text: a `SIGNING_FAILED` is a decline exactly when its\n * `params.reason` is `user_rejected`, and every other SDK error is not one. The same holds for a\n * plain-object VIEW of an SDK error (`{ code: 'SIGNING_FAILED', params: { reason } }`, the shape\n * of an app's wrapper): a string `code` plus an object `params` is decided by the code alone, with\n * the wallet code list above still honoured for a view that is not branded, and its English is\n * never read. This works without `instanceof`, so it is safe across two copies of the SDK.\n *\n * @example\n * ```ts\n * try {\n * await wallet.connect();\n * } catch (error) {\n * if (isWalletUserRejection(error)) return; // the person said no: not an error to report\n * report(error);\n * }\n * ```\n */\nexport function isWalletUserRejection(value: unknown): boolean {\n if (isGalaErrorLike(value)) {\n if (value.code === 'SIGNING_FAILED') return value.params['reason'] === 'user_rejected';\n return !hasGalaErrorBrand(value) && REJECTION_CODES.includes(value.code);\n }\n if (isRecord(value)) {\n if (REJECTION_CODES.includes(value['code']) || value['name'] === REJECTION_NAME) return true;\n }\n return textsOf(value).some(wordsADecline);\n}\n\n/** The longest wallet code kept: real ones (`4001`, `ACTION_REJECTED`) are short. */\nconst MAX_WALLET_CODE_LENGTH = 64;\n\n/**\n * The code a wallet put on its error: an EIP-1193 / JSON-RPC number (`4001`, `-32603`) or an\n * ethers / viem string (`'ACTION_REJECTED'`), read from the error's own top-level `code`. Anything\n * else (no code, a non-finite number, an empty or very long string, an object) is `undefined`, so\n * the value is always a safe primitive. Used for `GalaSDKError.walletCode`.\n *\n * @example\n * ```ts\n * walletDeclineCode({ code: 4001, message: 'User rejected the request.' }); // 4001\n * walletDeclineCode(new Error('locked')); // undefined\n * ```\n */\nexport function walletDeclineCode(value: unknown): number | string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { code } = value as { code?: unknown };\n if (typeof code === 'number') return Number.isFinite(code) ? code : undefined;\n if (typeof code === 'string' && code.length > 0 && code.length <= MAX_WALLET_CODE_LENGTH) {\n return code;\n }\n return undefined;\n}\n"],"mappings":"A,0EAaA,MAAMA,EAAsC,CAAC,KAAM,kBAAmB,eAAe,EAW/EC,EAAuC,CAC3C,gBACA,cACA,cACA,uBACA,mBACA,mBACA,kBACA,YACA,UACF,EAGMC,EAA+B,CACnC,UACA,UACA,eACA,UACA,eACA,QACF,EAKA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAEA,SAASC,EAAQ,EAAgB,EAAQ,EAAa,CAGpD,OAFI,OAAOD,GAAU,SAAiB,CAACA,CAAK,EACxC,CAACD,EAASC,CAAK,GAAKE,GAAS,EAAuB,CAAC,EAClDJ,EAAU,QAAS,GAAQG,EAAQD,EAAMG,GAAMD,EAAQ,CAAC,CAAC,CAClE,CAEA,SAASE,EAAc,EAAuB,CAC5C,IAAMC,EAAQC,EAAK,YAAY,EAC/B,OACET,EAAkB,KAAM,GAAWQ,EAAM,SAASE,CAAM,CAAC,GACxDF,EAAM,SAAS,WAAW,GAAKA,EAAM,SAAS,QAAQ,CAE3D,CAiCA,SAAgBG,EAAsB,EAAyB,CAQ7D,OAPIC,EAAgBT,CAAK,EACnBA,EAAM,OAAS,iBAAyBA,EAAM,OAAOU,SAAc,gBAChE,CAACC,EAAkBX,CAAK,GAAKJ,EAAgB,SAASI,EAAM,IAAI,EAErED,EAASC,CAAK,IACZJ,EAAgB,SAASI,EAAMY,IAAO,GAAKZ,EAAMa,OAAY,4BAAuB,GAEnFZ,EAAQD,CAAK,CAAC,CAAC,KAAKI,CAAa,CAC1C,CAiBA,SAAgBU,EAAkB,EAA6C,CAC7E,GAAI,OAAOd,GAAU,WAAYA,EAAgB,OACjD,GAAM,CAAE,QAASA,EACjB,GAAI,OAAOe,GAAS,SAAU,OAAO,OAAO,SAASA,CAAI,EAAIA,EAAO,IAAA,GACpE,GAAI,OAAOA,GAAS,UAAYA,EAAK,OAAS,GAAKA,EAAK,QAAU,GAChE,OAAOA,CAGX,C"}
@@ -1,2 +1,2 @@
1
- const e=`1.0.0`;export{e as GALA_CORE_SDK_VERSION};
1
+ const e=`1.1.0-beta.1`;export{e as GALA_CORE_SDK_VERSION};
2
2
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":["GALA_CORE_SDK_VERSION"],"sources":["../../src/version.ts"],"sourcesContent":["declare const __GALA_CORE_SDK_VERSION__: string | undefined;\n\n/**\n * The `@gala-chain/gala-core-sdk` package version, embedded by the bundler, with a source-test\n * fallback. It is the version in the default `User-Agent` (`GalaChain-SDK/<version>`) of every SDK\n * request, whichever product SDK sends it.\n */\nexport const GALA_CORE_SDK_VERSION =\n typeof __GALA_CORE_SDK_VERSION__ === 'string' ? __GALA_CORE_SDK_VERSION__ : '1.0.0';\n"],"mappings":"AAOA,MAAaA,EAAA"}
1
+ {"version":3,"file":"version.js","names":["GALA_CORE_SDK_VERSION"],"sources":["../../src/version.ts"],"sourcesContent":["declare const __GALA_CORE_SDK_VERSION__: string | undefined;\n\n/**\n * The `@gala-chain/gala-core-sdk` package version, embedded by the bundler, with a source-test\n * fallback. It is the version in the default `User-Agent` (`GalaChain-SDK/<version>`) of every SDK\n * request, whichever product SDK sends it.\n */\nexport const GALA_CORE_SDK_VERSION =\n typeof __GALA_CORE_SDK_VERSION__ === 'string' ? __GALA_CORE_SDK_VERSION__ : '1.1.0-beta.1';\n"],"mappings":"AAOA,MAAaA,EAAA,e"}
@@ -1 +1 @@
1
- {"version":3,"file":"wallet.js","names":["isRecord","GALA_ERROR_BRAND","isRecord$1","value","hasGalaErrorBrand","isGalaErrorLike","\"code\"","\"params\"","REJECTION_CODES","REJECTION_PHRASES","TEXT_KEYS","isRecord","textsOf","depth","key","wordsADecline","lower","text","phrase","isWalletUserRejection","\"reason\"","\"name\"","walletDeclineCode","code"],"sources":["../../src/utils/error_brand.ts","../../src/utils/wallet_rejection.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","/**\n * What the SDK knows about a failure thrown by a WALLET (the signer an app supplies, or wallet\n * code of the app's own): the code the wallet put on it, and whether it means the person declined.\n * Both read only the wallet's own error value; neither shows or forwards its text.\n */\n\nimport { hasGalaErrorBrand, isGalaErrorLike } from './error_brand.js';\n\n// This module is the whole of the light `@gala-chain/gala-core-sdk/wallet` entry (and the main\n// entry re-exports it, so there is one implementation). It must stay dependency-free: it may\n// import only `./error_brand.js`, never the error catalog, `GalaSDKError` or the main index.\n\n/** Codes the EIP-1193 / ethers / viem families use for \"the person declined in the wallet\". */\nconst REJECTION_CODES: readonly unknown[] = [4001, 'ACTION_REJECTED', 'USER_REJECTED'];\n\n/** The `name` viem / wagmi give the error of a declined request. */\nconst REJECTION_NAME = 'UserRejectedRequestError';\n\n/**\n * Wordings of a decline, matched case-insensitively as substrings. This is a LAST RESORT for\n * wallets that set neither a `code` nor a `name`: it reads a third party's text, so it is broad on\n * purpose (a superset of the matchers the Gala wallet and gSwap web app used) and can in principle\n * match an unrelated message that uses these words.\n */\nconst REJECTION_PHRASES: readonly string[] = [\n 'user rejected',\n 'user denied',\n 'user cancel',\n 'rejected the request',\n 'request rejected',\n 'rejected by user',\n 'action_rejected',\n 'cancelled',\n 'canceled',\n];\n\n/** Properties wallets nest their text under (EIP-1193, ethers, viem, Gala wallet). */\nconst TEXT_KEYS: readonly string[] = [\n 'message',\n 'Message',\n 'shortMessage',\n 'details',\n 'errorDetails',\n 'reason',\n];\n\n/** Wallet errors nest their text at most a level or two deep; the bound also stops a cyclic object. */\nconst MAX_TEXT_DEPTH = 3;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction textsOf(value: unknown, depth = 0): string[] {\n if (typeof value === 'string') return [value];\n if (!isRecord(value) || depth >= MAX_TEXT_DEPTH) return [];\n return TEXT_KEYS.flatMap((key) => textsOf(value[key], depth + 1));\n}\n\nfunction wordsADecline(text: string): boolean {\n const lower = text.toLowerCase();\n return (\n REJECTION_PHRASES.some((phrase) => lower.includes(phrase)) ||\n (lower.includes('signature') && lower.includes('cancel'))\n );\n}\n\n/**\n * True when a wallet's error (or just its message text) says the person DECLINED the request in\n * their wallet. This is exactly the test behind `SIGNING_FAILED` with `params.reason ===\n * 'user_rejected'`, exported for wallet code outside the SDK (connect and registration flows, a\n * v1 write path) so an app keeps no matcher of its own.\n *\n * It is decided from the wallet's own fields first: a `code` of `4001` (EIP-1193), `'ACTION_REJECTED'`\n * (ethers) or `'USER_REJECTED'`, or `name === 'UserRejectedRequestError'` (viem). Only when those are\n * absent is the wallet's TEXT read (`message`, `Message`, `shortMessage`, `details`, `errorDetails`,\n * `reason`, up to three levels deep, or a bare string): \"user rejected\", \"user denied\", \"user\n * cancelled\", \"request rejected\", \"rejected by user\", \"rejected the request\", \"cancelled\" /\n * \"canceled\", or a \"signature ... cancel\" sentence. The wording fallback is a last resort for\n * wallets that do not set codes; prefer `code` and `name` wherever you control the wallet.\n *\n * An SDK error is never read by its text: a `SIGNING_FAILED` is a decline exactly when its\n * `params.reason` is `user_rejected`, and every other SDK error is not one. The same holds for a\n * plain-object VIEW of an SDK error (`{ code: 'SIGNING_FAILED', params: { reason } }`, the shape\n * of an app's wrapper): a string `code` plus an object `params` is decided by the code alone, with\n * the wallet code list above still honoured for a view that is not branded, and its English is\n * never read. This works without `instanceof`, so it is safe across two copies of the SDK.\n *\n * @example\n * ```ts\n * try {\n * await wallet.connect();\n * } catch (error) {\n * if (isWalletUserRejection(error)) return; // the person said no: not an error to report\n * report(error);\n * }\n * ```\n */\nexport function isWalletUserRejection(value: unknown): boolean {\n if (isGalaErrorLike(value)) {\n if (value.code === 'SIGNING_FAILED') return value.params['reason'] === 'user_rejected';\n return !hasGalaErrorBrand(value) && REJECTION_CODES.includes(value.code);\n }\n if (isRecord(value)) {\n if (REJECTION_CODES.includes(value['code']) || value['name'] === REJECTION_NAME) return true;\n }\n return textsOf(value).some(wordsADecline);\n}\n\n/** The longest wallet code kept: real ones (`4001`, `ACTION_REJECTED`) are short. */\nconst MAX_WALLET_CODE_LENGTH = 64;\n\n/**\n * The code a wallet put on its error: an EIP-1193 / JSON-RPC number (`4001`, `-32603`) or an\n * ethers / viem string (`'ACTION_REJECTED'`), read from the error's own top-level `code`. Anything\n * else (no code, a non-finite number, an empty or very long string, an object) is `undefined`, so\n * the value is always a safe primitive. Used for `GalaSDKError.walletCode`.\n *\n * @example\n * ```ts\n * walletDeclineCode({ code: 4001, message: 'User rejected the request.' }); // 4001\n * walletDeclineCode(new Error('locked')); // undefined\n * ```\n */\nexport function walletDeclineCode(value: unknown): number | string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { code } = value as { code?: unknown };\n if (typeof code === 'number') return Number.isFinite(code) ? code : undefined;\n if (typeof code === 'string' && code.length > 0 && code.length <= MAX_WALLET_CODE_LENGTH) {\n return code;\n }\n return undefined;\n}\n"],"mappings":"AAYA,MAAaC,EAAkC,OAAO,IAAI,iCAAiC,EAQ3F,SAASD,EAAS,EAAuD,CACvE,OAAO,OAAOG,GAAU,YAAYA,CACtC,CAGA,SAAgBC,EAAkB,EAAyB,CACzD,OAAOJ,EAASG,CAAK,GAAKA,EAAMF,KAAsB,EACxD,CAcA,SAAgBI,EAAgB,EAAyC,CAEvE,OADID,EAAkBD,CAAK,EAAU,GAEnCH,EAASG,CAAK,GACd,OAAOA,EAAMG,MAAY,UACzBN,EAASG,EAAMI,MAAS,GACxB,CAAC,MAAM,QAAQJ,EAAMI,MAAS,CAElC,CCpCA,MAAMC,EAAsC,CAAC,KAAM,kBAAmB,eAAe,EAW/EC,EAAuC,CAC3C,gBACA,cACA,cACA,uBACA,mBACA,mBACA,kBACA,YACA,UACF,EAGMC,EAA+B,CACnC,UACA,UACA,eACA,UACA,eACA,QACF,EAKA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOR,GAAU,YAAYA,CACtC,CAEA,SAASS,EAAQ,EAAgB,EAAQ,EAAa,CAGpD,OAFI,OAAOT,GAAU,SAAiB,CAACA,CAAK,EACxC,CAACQ,EAASR,CAAK,GAAKU,GAAS,EAAuB,CAAC,EAClDH,EAAU,QAAS,GAAQE,EAAQT,EAAMW,GAAMD,EAAQ,CAAC,CAAC,CAClE,CAEA,SAASE,EAAc,EAAuB,CAC5C,IAAMC,EAAQC,EAAK,YAAY,EAC/B,OACER,EAAkB,KAAM,GAAWO,EAAM,SAASE,CAAM,CAAC,GACxDF,EAAM,SAAS,WAAW,GAAKA,EAAM,SAAS,QAAQ,CAE3D,CAiCA,SAAgBG,EAAsB,EAAyB,CAQ7D,OAPId,EAAgBF,CAAK,EACnBA,EAAM,OAAS,iBAAyBA,EAAM,OAAOiB,SAAc,gBAChE,CAAChB,EAAkBD,CAAK,GAAKK,EAAgB,SAASL,EAAM,IAAI,EAErEQ,EAASR,CAAK,IACZK,EAAgB,SAASL,EAAMG,IAAO,GAAKH,EAAMkB,OAAY,4BAAuB,GAEnFT,EAAQT,CAAK,CAAC,CAAC,KAAKY,CAAa,CAC1C,CAiBA,SAAgBO,EAAkB,EAA6C,CAC7E,GAAI,OAAOnB,GAAU,WAAYA,EAAgB,OACjD,GAAM,CAAE,QAASA,EACjB,GAAI,OAAOoB,GAAS,SAAU,OAAO,OAAO,SAASA,CAAI,EAAIA,EAAO,IAAA,GACpE,GAAI,OAAOA,GAAS,UAAYA,EAAK,OAAS,GAAKA,EAAK,QAAU,GAChE,OAAOA,CAGX"}
1
+ {"version":3,"file":"wallet.js","names":["isRecord","GALA_ERROR_BRAND","isRecord$1","value","hasGalaErrorBrand","isGalaErrorLike","\"code\"","\"params\"","REJECTION_CODES","REJECTION_PHRASES","TEXT_KEYS","isRecord","textsOf","depth","key","wordsADecline","lower","text","phrase","isWalletUserRejection","\"reason\"","\"name\"","walletDeclineCode","code"],"sources":["../../src/utils/error_brand.ts","../../src/utils/wallet_rejection.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","/**\n * What the SDK knows about a failure thrown by a WALLET (the signer an app supplies, or wallet\n * code of the app's own): the code the wallet put on it, and whether it means the person declined.\n * Both read only the wallet's own error value; neither shows or forwards its text.\n */\n\nimport { hasGalaErrorBrand, isGalaErrorLike } from './error_brand.js';\n\n// This module is the whole of the light `@gala-chain/gala-core-sdk/wallet` entry (and the main\n// entry re-exports it, so there is one implementation). It must stay dependency-free: it may\n// import only `./error_brand.js`, never the error catalog, `GalaSDKError` or the main index.\n\n/** Codes the EIP-1193 / ethers / viem families use for \"the person declined in the wallet\". */\nconst REJECTION_CODES: readonly unknown[] = [4001, 'ACTION_REJECTED', 'USER_REJECTED'];\n\n/** The `name` viem / wagmi give the error of a declined request. */\nconst REJECTION_NAME = 'UserRejectedRequestError';\n\n/**\n * Wordings of a decline, matched case-insensitively as substrings. This is a LAST RESORT for\n * wallets that set neither a `code` nor a `name`: it reads a third party's text, so it is broad on\n * purpose (a superset of the matchers the Gala wallet and gSwap web app used) and can in principle\n * match an unrelated message that uses these words.\n */\nconst REJECTION_PHRASES: readonly string[] = [\n 'user rejected',\n 'user denied',\n 'user cancel',\n 'rejected the request',\n 'request rejected',\n 'rejected by user',\n 'action_rejected',\n 'cancelled',\n 'canceled',\n];\n\n/** Properties wallets nest their text under (EIP-1193, ethers, viem, Gala wallet). */\nconst TEXT_KEYS: readonly string[] = [\n 'message',\n 'Message',\n 'shortMessage',\n 'details',\n 'errorDetails',\n 'reason',\n];\n\n/** Wallet errors nest their text at most a level or two deep; the bound also stops a cyclic object. */\nconst MAX_TEXT_DEPTH = 3;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction textsOf(value: unknown, depth = 0): string[] {\n if (typeof value === 'string') return [value];\n if (!isRecord(value) || depth >= MAX_TEXT_DEPTH) return [];\n return TEXT_KEYS.flatMap((key) => textsOf(value[key], depth + 1));\n}\n\nfunction wordsADecline(text: string): boolean {\n const lower = text.toLowerCase();\n return (\n REJECTION_PHRASES.some((phrase) => lower.includes(phrase)) ||\n (lower.includes('signature') && lower.includes('cancel'))\n );\n}\n\n/**\n * True when a wallet's error (or just its message text) says the person DECLINED the request in\n * their wallet. This is exactly the test behind `SIGNING_FAILED` with `params.reason ===\n * 'user_rejected'`, exported for wallet code outside the SDK (connect and registration flows, a\n * v1 write path) so an app keeps no matcher of its own.\n *\n * It is decided from the wallet's own fields first: a `code` of `4001` (EIP-1193), `'ACTION_REJECTED'`\n * (ethers) or `'USER_REJECTED'`, or `name === 'UserRejectedRequestError'` (viem). Only when those are\n * absent is the wallet's TEXT read (`message`, `Message`, `shortMessage`, `details`, `errorDetails`,\n * `reason`, up to three levels deep, or a bare string): \"user rejected\", \"user denied\", \"user\n * cancelled\", \"request rejected\", \"rejected by user\", \"rejected the request\", \"cancelled\" /\n * \"canceled\", or a \"signature ... cancel\" sentence. The wording fallback is a last resort for\n * wallets that do not set codes; prefer `code` and `name` wherever you control the wallet.\n *\n * An SDK error is never read by its text: a `SIGNING_FAILED` is a decline exactly when its\n * `params.reason` is `user_rejected`, and every other SDK error is not one. The same holds for a\n * plain-object VIEW of an SDK error (`{ code: 'SIGNING_FAILED', params: { reason } }`, the shape\n * of an app's wrapper): a string `code` plus an object `params` is decided by the code alone, with\n * the wallet code list above still honoured for a view that is not branded, and its English is\n * never read. This works without `instanceof`, so it is safe across two copies of the SDK.\n *\n * @example\n * ```ts\n * try {\n * await wallet.connect();\n * } catch (error) {\n * if (isWalletUserRejection(error)) return; // the person said no: not an error to report\n * report(error);\n * }\n * ```\n */\nexport function isWalletUserRejection(value: unknown): boolean {\n if (isGalaErrorLike(value)) {\n if (value.code === 'SIGNING_FAILED') return value.params['reason'] === 'user_rejected';\n return !hasGalaErrorBrand(value) && REJECTION_CODES.includes(value.code);\n }\n if (isRecord(value)) {\n if (REJECTION_CODES.includes(value['code']) || value['name'] === REJECTION_NAME) return true;\n }\n return textsOf(value).some(wordsADecline);\n}\n\n/** The longest wallet code kept: real ones (`4001`, `ACTION_REJECTED`) are short. */\nconst MAX_WALLET_CODE_LENGTH = 64;\n\n/**\n * The code a wallet put on its error: an EIP-1193 / JSON-RPC number (`4001`, `-32603`) or an\n * ethers / viem string (`'ACTION_REJECTED'`), read from the error's own top-level `code`. Anything\n * else (no code, a non-finite number, an empty or very long string, an object) is `undefined`, so\n * the value is always a safe primitive. Used for `GalaSDKError.walletCode`.\n *\n * @example\n * ```ts\n * walletDeclineCode({ code: 4001, message: 'User rejected the request.' }); // 4001\n * walletDeclineCode(new Error('locked')); // undefined\n * ```\n */\nexport function walletDeclineCode(value: unknown): number | string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { code } = value as { code?: unknown };\n if (typeof code === 'number') return Number.isFinite(code) ? code : undefined;\n if (typeof code === 'string' && code.length > 0 && code.length <= MAX_WALLET_CODE_LENGTH) {\n return code;\n }\n return undefined;\n}\n"],"mappings":"AAYA,MAAaC,EAAkC,OAAO,IAAI,iCAAiC,EAQ3F,SAASD,EAAS,EAAuD,CACvE,OAAO,OAAOG,GAAU,YAAYA,CACtC,CAGA,SAAgBC,EAAkB,EAAyB,CACzD,OAAOJ,EAASG,CAAK,GAAKA,EAAMF,KAAsB,EACxD,CAcA,SAAgBI,EAAgB,EAAyC,CAEvE,OADID,EAAkBD,CAAK,EAAU,GAEnCH,EAASG,CAAK,GACd,OAAOA,EAAMG,MAAY,UACzBN,EAASG,EAAMI,MAAS,GACxB,CAAC,MAAM,QAAQJ,EAAMI,MAAS,CAElC,CCpCA,MAAMC,EAAsC,CAAC,KAAM,kBAAmB,eAAe,EAW/EC,EAAuC,CAC3C,gBACA,cACA,cACA,uBACA,mBACA,mBACA,kBACA,YACA,UACF,EAGMC,EAA+B,CACnC,UACA,UACA,eACA,UACA,eACA,QACF,EAKA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOR,GAAU,YAAYA,CACtC,CAEA,SAASS,EAAQ,EAAgB,EAAQ,EAAa,CAGpD,OAFI,OAAOT,GAAU,SAAiB,CAACA,CAAK,EACxC,CAACQ,EAASR,CAAK,GAAKU,GAAS,EAAuB,CAAC,EAClDH,EAAU,QAAS,GAAQE,EAAQT,EAAMW,GAAMD,EAAQ,CAAC,CAAC,CAClE,CAEA,SAASE,EAAc,EAAuB,CAC5C,IAAMC,EAAQC,EAAK,YAAY,EAC/B,OACER,EAAkB,KAAM,GAAWO,EAAM,SAASE,CAAM,CAAC,GACxDF,EAAM,SAAS,WAAW,GAAKA,EAAM,SAAS,QAAQ,CAE3D,CAiCA,SAAgBG,EAAsB,EAAyB,CAQ7D,OAPId,EAAgBF,CAAK,EACnBA,EAAM,OAAS,iBAAyBA,EAAM,OAAOiB,SAAc,gBAChE,CAAChB,EAAkBD,CAAK,GAAKK,EAAgB,SAASL,EAAM,IAAI,EAErEQ,EAASR,CAAK,IACZK,EAAgB,SAASL,EAAMG,IAAO,GAAKH,EAAMkB,OAAY,4BAAuB,GAEnFT,EAAQT,CAAK,CAAC,CAAC,KAAKY,CAAa,CAC1C,CAiBA,SAAgBO,EAAkB,EAA6C,CAC7E,GAAI,OAAOnB,GAAU,WAAYA,EAAgB,OACjD,GAAM,CAAE,QAASA,EACjB,GAAI,OAAOoB,GAAS,SAAU,OAAO,OAAO,SAASA,CAAI,EAAIA,EAAO,IAAA,GACpE,GAAI,OAAOA,GAAS,UAAYA,EAAK,OAAS,GAAKA,EAAK,QAAU,GAChE,OAAOA,CAGX,C"}
@@ -1,2 +1,2 @@
1
- import e from"../_virtual/_@oxc-project_runtime@0.153.0/helpers/esm/defineProperty.js";import{GalaSDKError as t}from"../classes/gala_sdk_error.js";import{galaChainUserRef as n}from"./identity.js";import{fetchRequestor as r,validateTimeoutMs as i}from"../utils/transport.js";import{assertUniqueKey as a,createUniqueKey as o,resolveUniqueKeyPrefix as s}from"../utils/unique_key.js";import{lockExpires as c,lockName as l,lockTokenDto as u,unlockTokenDto as d}from"./lock.js";import{submitWrite as f}from"./submit.js";import{checkQuantity as p,resolveToken as m}from"./token_ref.js";import{GALA_TOKEN_CLASS_KEY as h,burnTokensDto as g,transferTokenDto as _}from"./transfer.js";import{GATEWAY_WRITE_BATCH_LIMITS as v}from"./types.js";var y=class{constructor(a){e(this,`walletAddress`,void 0),e(this,`transport`,void 0),e(this,`uniqueKeyPrefix`,void 0),e(this,`tokenNameResolver`,void 0);let{signer:o,gatewayBaseUrl:c,httpRequestor:l,tokenNameResolver:u}=a;if(typeof o!=`object`||!o||typeof o.signObject!=`function`)throw new t(`INVALID_WRITES_OPTION`,{option:`signer`});if(typeof c!=`string`)throw new t(`INVALID_WRITES_OPTION`,{option:`gatewayBaseUrl`});if(l!==void 0&&typeof l!=`function`)throw new t(`INVALID_WRITES_OPTION`,{option:`httpRequestor`});if(u!==void 0&&(typeof u!=`object`||!u||typeof u.resolveTokenClassKey!=`function`))throw new t(`INVALID_WRITES_OPTION`,{option:`tokenNameResolver`});this.walletAddress=n(a.walletAddress,`walletAddress`),this.uniqueKeyPrefix=s(a.uniqueKeyPrefix),this.tokenNameResolver=u,this.transport={gatewayBaseUrl:c.replace(/\/+$/u,``),signer:o,requestor:l??r,timeoutMs:i(a.requestTimeoutMs??3e4,`requestTimeoutMs`),wire:a.wire}}transferGala(e){return this.transferToken({to:e.to,quantity:e.quantity,tokenClassKey:h,uniqueKey:e.uniqueKey})}async transferToken(e){let t=n(e.to,`to`),r=p(e,``),i=this.uniqueKeyOf(e.uniqueKey),a=await this.resolveOne(r);return this.submit(`TransferToken`,_(this.walletAddress,t,a,i),i)}async burnTokens(e){let t=this.checkBatch(`BurnTokens`,e.tokens),n=this.uniqueKeyOf(e.uniqueKey),r=await this.resolveAll(t);return this.submit(`BurnTokens`,g(r,n),n)}async lockTokens(e){let t=e.lockAuthority===void 0?this.walletAddress:n(e.lockAuthority,`lockAuthority`),r=c(e.expires),i=l(e.name),a=this.checkBatch(`LockToken`,e.tokens),o=this.uniqueKeyOf(e.uniqueKey),s=await this.resolveAll(a);return this.submit(`LockToken`,u(t,this.walletAddress,s,o,r,i),o)}async unlockTokens(e){let t=l(e.name),n=this.checkBatch(`UnlockToken`,e.tokens),r=this.uniqueKeyOf(e.uniqueKey),i=await this.resolveAll(n);return this.submit(`UnlockToken`,d(this.walletAddress,i,r,t),r)}uniqueKeyOf(e){return e===void 0?o(this.uniqueKeyPrefix):(a(e),e)}checkBatch(e,n){let r=v[e],i=Array.isArray(n)?n.length:0;if(i<1||i>r)throw new t(`INVALID_TOKEN_BATCH`,{method:e,count:i,max:r});return n.map((e,t)=>p(e,`tokens[${t}].`))}async resolveOne(e){return{quantity:e.quantity,key:await m(e.token,this.tokenNameResolver)}}async resolveAll(e){let t=[];for(let n of e)t.push(await this.resolveOne(n));return t}submit(e,t,n){return f(this.transport,e,t,n)}};export{y as GatewayWrites};
1
+ import e from"../_virtual/_@oxc-project_runtime@0.154.0/helpers/esm/defineProperty.js";import{GalaSDKError as t}from"../classes/gala_sdk_error.js";import{galaChainUserRef as n}from"./identity.js";import{fetchRequestor as r,validateTimeoutMs as i}from"../utils/transport.js";import{assertUniqueKey as a,createUniqueKey as o,resolveUniqueKeyPrefix as s}from"../utils/unique_key.js";import{lockExpires as c,lockName as l,lockTokenDto as u,unlockTokenDto as d}from"./lock.js";import{submitWrite as f}from"./submit.js";import{checkQuantity as p,resolveToken as m}from"./token_ref.js";import{GALA_TOKEN_CLASS_KEY as h,burnTokensDto as g,transferTokenDto as _}from"./transfer.js";import{GATEWAY_WRITE_BATCH_LIMITS as v}from"./types.js";var y=class{constructor(a){e(this,`walletAddress`,void 0),e(this,`transport`,void 0),e(this,`uniqueKeyPrefix`,void 0),e(this,`tokenNameResolver`,void 0);let{signer:o,gatewayBaseUrl:c,httpRequestor:l,tokenNameResolver:u}=a;if(typeof o!=`object`||!o||typeof o.signObject!=`function`)throw new t(`INVALID_WRITES_OPTION`,{option:`signer`});if(typeof c!=`string`)throw new t(`INVALID_WRITES_OPTION`,{option:`gatewayBaseUrl`});if(l!==void 0&&typeof l!=`function`)throw new t(`INVALID_WRITES_OPTION`,{option:`httpRequestor`});if(u!==void 0&&(typeof u!=`object`||!u||typeof u.resolveTokenClassKey!=`function`))throw new t(`INVALID_WRITES_OPTION`,{option:`tokenNameResolver`});this.walletAddress=n(a.walletAddress,`walletAddress`),this.uniqueKeyPrefix=s(a.uniqueKeyPrefix),this.tokenNameResolver=u,this.transport={gatewayBaseUrl:c.replace(/\/+$/u,``),signer:o,requestor:l??r,timeoutMs:i(a.requestTimeoutMs??3e4,`requestTimeoutMs`),wire:a.wire}}transferGala(e){return this.transferToken({to:e.to,quantity:e.quantity,tokenClassKey:h,uniqueKey:e.uniqueKey})}async transferToken(e){let t=n(e.to,`to`),r=p(e,``),i=this.uniqueKeyOf(e.uniqueKey),a=await this.resolveOne(r);return this.submit(`TransferToken`,_(this.walletAddress,t,a,i),i)}async burnTokens(e){let t=this.checkBatch(`BurnTokens`,e.tokens),n=this.uniqueKeyOf(e.uniqueKey),r=await this.resolveAll(t);return this.submit(`BurnTokens`,g(r,n),n)}async lockTokens(e){let t=e.lockAuthority===void 0?this.walletAddress:n(e.lockAuthority,`lockAuthority`),r=c(e.expires),i=l(e.name),a=this.checkBatch(`LockToken`,e.tokens),o=this.uniqueKeyOf(e.uniqueKey),s=await this.resolveAll(a);return this.submit(`LockToken`,u(t,this.walletAddress,s,o,r,i),o)}async unlockTokens(e){let t=l(e.name),n=this.checkBatch(`UnlockToken`,e.tokens),r=this.uniqueKeyOf(e.uniqueKey),i=await this.resolveAll(n);return this.submit(`UnlockToken`,d(this.walletAddress,i,r,t),r)}uniqueKeyOf(e){return e===void 0?o(this.uniqueKeyPrefix):(a(e),e)}checkBatch(e,n){let r=v[e],i=Array.isArray(n)?n.length:0;if(i<1||i>r)throw new t(`INVALID_TOKEN_BATCH`,{method:e,count:i,max:r});return n.map((e,t)=>p(e,`tokens[${t}].`))}async resolveOne(e){return{quantity:e.quantity,key:await m(e.token,this.tokenNameResolver)}}async resolveAll(e){let t=[];for(let n of e)t.push(await this.resolveOne(n));return t}submit(e,t,n){return f(this.transport,e,t,n)}};export{y as GatewayWrites};
2
2
  //# sourceMappingURL=gateway_writes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"gateway_writes.js","names":["_defineProperty","GatewayWrites","options","signer","GalaSDKError","gatewayBaseUrl","httpRequestor","tokenNameResolver","galaChainUserRef","resolveUniqueKeyPrefix","fetchRequestor","validateTimeoutMs","input","GALA_TOKEN_CLASS_KEY","to","checked","checkQuantity","uniqueKey","token","transferTokenDto","tokens","burnTokensDto","lockAuthority","expires","lockExpires","name","lockName","lockTokenDto","unlockTokenDto","given","createUniqueKey","assertUniqueKey","max","GATEWAY_WRITE_BATCH_LIMITS","method","count","index","resolveToken","resolved","entry","submitWrite","dto"],"sources":["../../../src/writes/gateway_writes.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { fetchRequestor, validateTimeoutMs } from '../utils/transport.js';\nimport { assertUniqueKey, createUniqueKey, resolveUniqueKeyPrefix } from '../utils/unique_key.js';\nimport { galaChainUserRef } from './identity.js';\nimport { lockExpires, lockName, lockTokenDto, unlockTokenDto } from './lock.js';\nimport { submitWrite, type WriteTransport } from './submit.js';\nimport { checkQuantity, resolveToken, type CheckedQuantity } from './token_ref.js';\nimport {\n burnTokensDto,\n GALA_TOKEN_CLASS_KEY,\n transferTokenDto,\n type ResolvedQuantity,\n} from './transfer.js';\nimport {\n GATEWAY_WRITE_BATCH_LIMITS,\n type BurnTokensInput,\n type GatewayWriteMethod,\n type GatewayWriteReceipt,\n type GatewayWritesOptions,\n type LockTokensInput,\n type TokenNameResolver,\n type TokenQuantityInput,\n type TransferGalaInput,\n type TransferTokenInput,\n type UnlockTokensInput,\n} from './types.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Signed GalaChain token-contract writes through the gateway: transfer GALA, transfer a token,\n * burn, lock and unlock. React Native safe (no Node builtins, no ethers, no `@gala-chain/api`).\n *\n * Every write is checked completely BEFORE it is signed (recipient and owner spellings, the token,\n * the quantity, the `uniqueKey`, the batch), so a refused input costs no signature and no request.\n * The DTO is plain JSON with exactly the chain's fields; the signer signs it as it is (nothing,\n * least of all a signer hint, is added) and the body sent is what the signer returned. Quantities\n * are whole tokens and are signed exactly as written.\n *\n * @example\n * ```ts\n * const writes = new GatewayWrites({\n * gatewayBaseUrl: 'https://gateway-mainnet.galachain.com',\n * signer: new PrivateKeySigner(privateKey),\n * walletAddress: 'eth|70997970C51812dc3A010C7d01b50e0d17dc79C8',\n * });\n * const { transactionId, blockNumber } = await writes.transferGala({ to: 'client|abc', quantity: '1.5' });\n * ```\n */\nexport class GatewayWrites {\n /** The identity every write is made as, in the spelling the gateway receives. */\n public readonly walletAddress: string;\n private readonly transport: WriteTransport;\n private readonly uniqueKeyPrefix: string;\n private readonly tokenNameResolver: TokenNameResolver | undefined;\n\n /**\n * @throws GalaSDKError `INVALID_WRITES_OPTION` (a missing signer or base URL, a requestor that is\n * not a function, a resolver without `resolveTokenClassKey`), `INVALID_WALLET_ADDRESS`,\n * `INVALID_TIMEOUT`, `INVALID_UNIQUE_KEY_PREFIX`.\n */\n constructor(options: GatewayWritesOptions) {\n const { signer, gatewayBaseUrl, httpRequestor, tokenNameResolver } = options;\n if (typeof signer !== 'object' || signer === null || typeof signer.signObject !== 'function') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'signer' });\n }\n if (typeof gatewayBaseUrl !== 'string') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'gatewayBaseUrl' });\n }\n if (httpRequestor !== undefined && typeof httpRequestor !== 'function') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'httpRequestor' });\n }\n if (\n tokenNameResolver !== undefined &&\n (typeof tokenNameResolver !== 'object' ||\n tokenNameResolver === null ||\n typeof tokenNameResolver.resolveTokenClassKey !== 'function')\n ) {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'tokenNameResolver' });\n }\n this.walletAddress = galaChainUserRef(options.walletAddress, 'walletAddress');\n this.uniqueKeyPrefix = resolveUniqueKeyPrefix(options.uniqueKeyPrefix);\n this.tokenNameResolver = tokenNameResolver;\n this.transport = {\n gatewayBaseUrl: gatewayBaseUrl.replace(/\\/+$/u, ''),\n signer,\n requestor: httpRequestor ?? fetchRequestor,\n timeoutMs: validateTimeoutMs(\n options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs',\n ),\n wire: options.wire,\n };\n }\n\n /**\n * Transfer GALA (`GALA|Unit|none|none`, instance `\"0\"`) to `to`.\n *\n * @throws GalaSDKError pre-send: `INVALID_WALLET_ADDRESS`, `INVALID_QUANTITY`,\n * `INVALID_UNIQUE_KEY`, `SIGNING_FAILED`; in flight: `GATEWAY_WRITE_OUTCOME_UNKNOWN` (check\n * `error.uniqueKey`; never resend under a fresh key);\n * post-send: `GATEWAY_WRITE_REJECTED`, `GATEWAY_HTTP_ERROR`, `GATEWAY_RESPONSE_INVALID`.\n */\n public transferGala(input: TransferGalaInput): Promise<GatewayWriteReceipt> {\n return this.transferToken({\n to: input.to,\n quantity: input.quantity,\n tokenClassKey: GALA_TOKEN_CLASS_KEY,\n uniqueKey: input.uniqueKey,\n });\n }\n\n /**\n * Transfer one token to `to`.\n *\n * @throws GalaSDKError as {@link transferGala}, plus `INVALID_TOKEN_REFERENCE`,\n * `NO_TOKEN_NAME_RESOLVER`, `TOKEN_NAME_RESOLUTION_FAILED`.\n */\n public async transferToken(input: TransferTokenInput): Promise<GatewayWriteReceipt> {\n const to = galaChainUserRef(input.to, 'to');\n const checked = checkQuantity(input, '');\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const token = await this.resolveOne(checked);\n return this.submit(\n 'TransferToken',\n transferTokenDto(this.walletAddress, to, token, uniqueKey),\n uniqueKey,\n );\n }\n\n /**\n * Burn 1 to 50 tokens of the writer's. IRREVERSIBLE: burned tokens are gone.\n *\n * @throws GalaSDKError as {@link transferToken}, plus `INVALID_TOKEN_BATCH`.\n */\n public async burnTokens(input: BurnTokensInput): Promise<GatewayWriteReceipt> {\n const checked = this.checkBatch('BurnTokens', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit('BurnTokens', burnTokensDto(tokens, uniqueKey), uniqueKey);\n }\n\n /**\n * Lock 1 to 100 tokens of the writer's under one hold.\n *\n * @throws GalaSDKError as {@link burnTokens}, plus `INVALID_LOCK_EXPIRES`, `INVALID_LOCK_NAME`.\n */\n public async lockTokens(input: LockTokensInput): Promise<GatewayWriteReceipt> {\n const lockAuthority =\n input.lockAuthority === undefined\n ? this.walletAddress\n : galaChainUserRef(input.lockAuthority, 'lockAuthority');\n const expires = lockExpires(input.expires);\n const name = lockName(input.name);\n const checked = this.checkBatch('LockToken', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit(\n 'LockToken',\n lockTokenDto(lockAuthority, this.walletAddress, tokens, uniqueKey, expires, name),\n uniqueKey,\n );\n }\n\n /**\n * Unlock 1 to 100 tokens of the writer's from their hold.\n *\n * @throws GalaSDKError as {@link burnTokens}, plus `INVALID_LOCK_NAME`.\n */\n public async unlockTokens(input: UnlockTokensInput): Promise<GatewayWriteReceipt> {\n const name = lockName(input.name);\n const checked = this.checkBatch('UnlockToken', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit(\n 'UnlockToken',\n unlockTokenDto(this.walletAddress, tokens, uniqueKey, name),\n uniqueKey,\n );\n }\n\n /** The caller's key, checked, or a fresh one. */\n private uniqueKeyOf(given: string | undefined): string {\n if (given === undefined) return createUniqueKey(this.uniqueKeyPrefix);\n assertUniqueKey(given);\n return given;\n }\n\n /** Every token and quantity of a batch write, checked synchronously, in order. */\n private checkBatch(\n method: Exclude<GatewayWriteMethod, 'TransferToken'>,\n tokens: readonly TokenQuantityInput[],\n ): CheckedQuantity[] {\n const max = GATEWAY_WRITE_BATCH_LIMITS[method];\n const count = Array.isArray(tokens) ? tokens.length : 0;\n if (count < 1 || count > max) {\n throw new GalaSDKError('INVALID_TOKEN_BATCH', { method, count, max });\n }\n return tokens.map((input, index) => checkQuantity(input, `tokens[${index}].`));\n }\n\n private async resolveOne(checked: CheckedQuantity): Promise<ResolvedQuantity> {\n return {\n quantity: checked.quantity,\n key: await resolveToken(checked.token, this.tokenNameResolver),\n };\n }\n\n /** Resolves the checked tokens' names in order, one at a time (a resolver may be rate-limited). */\n private async resolveAll(checked: readonly CheckedQuantity[]): Promise<ResolvedQuantity[]> {\n const resolved: ResolvedQuantity[] = [];\n for (const entry of checked) resolved.push(await this.resolveOne(entry));\n return resolved;\n }\n\n private submit(\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n uniqueKey: string,\n ): Promise<GatewayWriteReceipt> {\n return submitWrite(this.transport, method, dto, uniqueKey);\n }\n}\n"],"mappings":"ytBAiDA,IAAaC,EAAb,KAA2B,CAYzB,YAAY,EAA+B,CAV3BD,EAAA,KAAA,gBAAA,IAAA,EAAA,EACCA,EAAA,KAAA,YAAA,IAAA,EAAA,EACAA,EAAA,KAAA,kBAAA,IAAA,EAAA,EACAA,EAAA,KAAA,oBAAA,IAAA,EAAA,EAQf,GAAM,CAAE,SAAQ,iBAAgB,gBAAe,qBAAsBE,EACrE,GAAI,OAAOC,GAAW,WAAYA,GAAmB,OAAOA,EAAO,YAAe,WAChF,MAAM,IAAIC,EAAa,wBAAyB,CAAE,OAAQ,QAAS,CAAC,EAEtE,GAAI,OAAOC,GAAmB,SAC5B,MAAM,IAAID,EAAa,wBAAyB,CAAE,OAAQ,gBAAiB,CAAC,EAE9E,GAAIE,IAAkB,IAAA,IAAa,OAAOA,GAAkB,WAC1D,MAAM,IAAIF,EAAa,wBAAyB,CAAE,OAAQ,eAAgB,CAAC,EAE7E,GACEG,IAAsB,IAAA,KACrB,OAAOA,GAAsB,WAC5BA,GACA,OAAOA,EAAkB,sBAAyB,YAEpD,MAAM,IAAIH,EAAa,wBAAyB,CAAE,OAAQ,mBAAoB,CAAC,EAEjF,KAAK,cAAgBI,EAAiBN,EAAQ,cAAe,eAAe,EAC5E,KAAK,gBAAkBO,EAAuBP,EAAQ,eAAe,EACrE,KAAK,kBAAoBK,EACzB,KAAK,UAAY,CACf,eAAgBF,EAAe,QAAQ,QAAS,EAAE,EAClD,SACA,UAAWC,GAAiBI,EAC5B,U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,KAAK,YAAYL,EAAM,SAAS,EAC5CQ,EAAS,MAAM,KAAK,WAAWL,CAAO,EAC5C,OAAO,KAAK,OACV,cACAa,EAAe,KAAK,cAAeR,EAAQH,EAAWQ,CAAI,EAC1DR,CACF,CACF,CAGA,YAAoB,EAAmC,CAGrD,OAFIY,IAAU,IAAA,GAAkBC,EAAgB,KAAK,eAAe,GACpEC,EAAgBF,CAAK,EACdA,EACT,CAGA,WACE,EACA,EACmB,CACnB,IAAMG,EAAMC,EAA2BC,GACjCC,EAAQ,MAAM,QAAQf,CAAM,EAAIA,EAAO,OAAS,EACtD,GAAIe,EAAQ,GAAKA,EAAQH,EACvB,MAAM,IAAI5B,EAAa,sBAAuB,CAAE,SAAQ,QAAO,KAAI,CAAC,EAEtE,OAAOgB,EAAO,KAAK,EAAO,IAAUJ,EAAcJ,EAAO,UAAUwB,EAAM,GAAG,CAAC,CAC/E,CAEA,MAAc,WAAW,EAAqD,CAC5E,MAAO,CACL,SAAUrB,EAAQ,SAClB,IAAK,MAAMsB,EAAatB,EAAQ,MAAO,KAAK,iBAAiB,CAC/D,CACF,CAGA,MAAc,WAAW,EAAkE,CACzF,IAAMuB,EAA+B,CAAC,EACtC,IAAK,IAAMC,KAASxB,EAASuB,EAAS,KAAK,MAAM,KAAK,WAAWC,CAAK,CAAC,EACvE,OAAOD,CACT,CAEA,OACE,EACA,EACA,EAC8B,CAC9B,OAAOE,EAAY,KAAK,UAAWN,EAAQO,EAAKxB,CAAS,CAC3D,CACF"}
1
+ {"version":3,"file":"gateway_writes.js","names":["_defineProperty","GatewayWrites","options","signer","GalaSDKError","gatewayBaseUrl","httpRequestor","tokenNameResolver","galaChainUserRef","resolveUniqueKeyPrefix","fetchRequestor","validateTimeoutMs","input","GALA_TOKEN_CLASS_KEY","to","checked","checkQuantity","uniqueKey","token","transferTokenDto","tokens","burnTokensDto","lockAuthority","expires","lockExpires","name","lockName","lockTokenDto","unlockTokenDto","given","createUniqueKey","assertUniqueKey","max","GATEWAY_WRITE_BATCH_LIMITS","method","count","index","resolveToken","resolved","entry","submitWrite","dto"],"sources":["../../../src/writes/gateway_writes.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { fetchRequestor, validateTimeoutMs } from '../utils/transport.js';\nimport { assertUniqueKey, createUniqueKey, resolveUniqueKeyPrefix } from '../utils/unique_key.js';\nimport { galaChainUserRef } from './identity.js';\nimport { lockExpires, lockName, lockTokenDto, unlockTokenDto } from './lock.js';\nimport { submitWrite, type WriteTransport } from './submit.js';\nimport { checkQuantity, resolveToken, type CheckedQuantity } from './token_ref.js';\nimport {\n burnTokensDto,\n GALA_TOKEN_CLASS_KEY,\n transferTokenDto,\n type ResolvedQuantity,\n} from './transfer.js';\nimport {\n GATEWAY_WRITE_BATCH_LIMITS,\n type BurnTokensInput,\n type GatewayWriteMethod,\n type GatewayWriteReceipt,\n type GatewayWritesOptions,\n type LockTokensInput,\n type TokenNameResolver,\n type TokenQuantityInput,\n type TransferGalaInput,\n type TransferTokenInput,\n type UnlockTokensInput,\n} from './types.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Signed GalaChain token-contract writes through the gateway: transfer GALA, transfer a token,\n * burn, lock and unlock. React Native safe (no Node builtins, no ethers, no `@gala-chain/api`).\n *\n * Every write is checked completely BEFORE it is signed (recipient and owner spellings, the token,\n * the quantity, the `uniqueKey`, the batch), so a refused input costs no signature and no request.\n * The DTO is plain JSON with exactly the chain's fields; the signer signs it as it is (nothing,\n * least of all a signer hint, is added) and the body sent is what the signer returned. Quantities\n * are whole tokens and are signed exactly as written.\n *\n * @example\n * ```ts\n * const writes = new GatewayWrites({\n * gatewayBaseUrl: 'https://gateway-mainnet.galachain.com',\n * signer: new PrivateKeySigner(privateKey),\n * walletAddress: 'eth|70997970C51812dc3A010C7d01b50e0d17dc79C8',\n * });\n * const { transactionId, blockNumber } = await writes.transferGala({ to: 'client|abc', quantity: '1.5' });\n * ```\n */\nexport class GatewayWrites {\n /** The identity every write is made as, in the spelling the gateway receives. */\n public readonly walletAddress: string;\n private readonly transport: WriteTransport;\n private readonly uniqueKeyPrefix: string;\n private readonly tokenNameResolver: TokenNameResolver | undefined;\n\n /**\n * @throws GalaSDKError `INVALID_WRITES_OPTION` (a missing signer or base URL, a requestor that is\n * not a function, a resolver without `resolveTokenClassKey`), `INVALID_WALLET_ADDRESS`,\n * `INVALID_TIMEOUT`, `INVALID_UNIQUE_KEY_PREFIX`.\n */\n constructor(options: GatewayWritesOptions) {\n const { signer, gatewayBaseUrl, httpRequestor, tokenNameResolver } = options;\n if (typeof signer !== 'object' || signer === null || typeof signer.signObject !== 'function') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'signer' });\n }\n if (typeof gatewayBaseUrl !== 'string') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'gatewayBaseUrl' });\n }\n if (httpRequestor !== undefined && typeof httpRequestor !== 'function') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'httpRequestor' });\n }\n if (\n tokenNameResolver !== undefined &&\n (typeof tokenNameResolver !== 'object' ||\n tokenNameResolver === null ||\n typeof tokenNameResolver.resolveTokenClassKey !== 'function')\n ) {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'tokenNameResolver' });\n }\n this.walletAddress = galaChainUserRef(options.walletAddress, 'walletAddress');\n this.uniqueKeyPrefix = resolveUniqueKeyPrefix(options.uniqueKeyPrefix);\n this.tokenNameResolver = tokenNameResolver;\n this.transport = {\n gatewayBaseUrl: gatewayBaseUrl.replace(/\\/+$/u, ''),\n signer,\n requestor: httpRequestor ?? fetchRequestor,\n timeoutMs: validateTimeoutMs(\n options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs',\n ),\n wire: options.wire,\n };\n }\n\n /**\n * Transfer GALA (`GALA|Unit|none|none`, instance `\"0\"`) to `to`.\n *\n * @throws GalaSDKError pre-send: `INVALID_WALLET_ADDRESS`, `INVALID_QUANTITY`,\n * `INVALID_UNIQUE_KEY`, `SIGNING_FAILED`; in flight: `GATEWAY_WRITE_OUTCOME_UNKNOWN` (check\n * `error.uniqueKey`; never resend under a fresh key);\n * post-send: `GATEWAY_WRITE_REJECTED`, `GATEWAY_HTTP_ERROR`, `GATEWAY_RESPONSE_INVALID`.\n */\n public transferGala(input: TransferGalaInput): Promise<GatewayWriteReceipt> {\n return this.transferToken({\n to: input.to,\n quantity: input.quantity,\n tokenClassKey: GALA_TOKEN_CLASS_KEY,\n uniqueKey: input.uniqueKey,\n });\n }\n\n /**\n * Transfer one token to `to`.\n *\n * @throws GalaSDKError as {@link transferGala}, plus `INVALID_TOKEN_REFERENCE`,\n * `NO_TOKEN_NAME_RESOLVER`, `TOKEN_NAME_RESOLUTION_FAILED`.\n */\n public async transferToken(input: TransferTokenInput): Promise<GatewayWriteReceipt> {\n const to = galaChainUserRef(input.to, 'to');\n const checked = checkQuantity(input, '');\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const token = await this.resolveOne(checked);\n return this.submit(\n 'TransferToken',\n transferTokenDto(this.walletAddress, to, token, uniqueKey),\n uniqueKey,\n );\n }\n\n /**\n * Burn 1 to 50 tokens of the writer's. IRREVERSIBLE: burned tokens are gone.\n *\n * @throws GalaSDKError as {@link transferToken}, plus `INVALID_TOKEN_BATCH`.\n */\n public async burnTokens(input: BurnTokensInput): Promise<GatewayWriteReceipt> {\n const checked = this.checkBatch('BurnTokens', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit('BurnTokens', burnTokensDto(tokens, uniqueKey), uniqueKey);\n }\n\n /**\n * Lock 1 to 100 tokens of the writer's under one hold.\n *\n * @throws GalaSDKError as {@link burnTokens}, plus `INVALID_LOCK_EXPIRES`, `INVALID_LOCK_NAME`.\n */\n public async lockTokens(input: LockTokensInput): Promise<GatewayWriteReceipt> {\n const lockAuthority =\n input.lockAuthority === undefined\n ? this.walletAddress\n : galaChainUserRef(input.lockAuthority, 'lockAuthority');\n const expires = lockExpires(input.expires);\n const name = lockName(input.name);\n const checked = this.checkBatch('LockToken', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit(\n 'LockToken',\n lockTokenDto(lockAuthority, this.walletAddress, tokens, uniqueKey, expires, name),\n uniqueKey,\n );\n }\n\n /**\n * Unlock 1 to 100 tokens of the writer's from their hold.\n *\n * @throws GalaSDKError as {@link burnTokens}, plus `INVALID_LOCK_NAME`.\n */\n public async unlockTokens(input: UnlockTokensInput): Promise<GatewayWriteReceipt> {\n const name = lockName(input.name);\n const checked = this.checkBatch('UnlockToken', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit(\n 'UnlockToken',\n unlockTokenDto(this.walletAddress, tokens, uniqueKey, name),\n uniqueKey,\n );\n }\n\n /** The caller's key, checked, or a fresh one. */\n private uniqueKeyOf(given: string | undefined): string {\n if (given === undefined) return createUniqueKey(this.uniqueKeyPrefix);\n assertUniqueKey(given);\n return given;\n }\n\n /** Every token and quantity of a batch write, checked synchronously, in order. */\n private checkBatch(\n method: Exclude<GatewayWriteMethod, 'TransferToken'>,\n tokens: readonly TokenQuantityInput[],\n ): CheckedQuantity[] {\n const max = GATEWAY_WRITE_BATCH_LIMITS[method];\n const count = Array.isArray(tokens) ? tokens.length : 0;\n if (count < 1 || count > max) {\n throw new GalaSDKError('INVALID_TOKEN_BATCH', { method, count, max });\n }\n return tokens.map((input, index) => checkQuantity(input, `tokens[${index}].`));\n }\n\n private async resolveOne(checked: CheckedQuantity): Promise<ResolvedQuantity> {\n return {\n quantity: checked.quantity,\n key: await resolveToken(checked.token, this.tokenNameResolver),\n };\n }\n\n /** Resolves the checked tokens' names in order, one at a time (a resolver may be rate-limited). */\n private async resolveAll(checked: readonly CheckedQuantity[]): Promise<ResolvedQuantity[]> {\n const resolved: ResolvedQuantity[] = [];\n for (const entry of checked) resolved.push(await this.resolveOne(entry));\n return resolved;\n }\n\n private submit(\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n uniqueKey: string,\n ): Promise<GatewayWriteReceipt> {\n return submitWrite(this.transport, method, dto, uniqueKey);\n }\n}\n"],"mappings":"A,ytBAiDA,IAAaC,EAAb,KAA2B,CAYzB,YAAY,EAA+B,CAV3BD,EAAA,KAAA,gBAAA,IAAA,EAAA,EACCA,EAAA,KAAA,YAAA,IAAA,EAAA,EACAA,EAAA,KAAA,kBAAA,IAAA,EAAA,EACAA,EAAA,KAAA,oBAAA,IAAA,EAAA,EAQf,GAAM,CAAE,SAAQ,iBAAgB,gBAAe,qBAAsBE,EACrE,GAAI,OAAOC,GAAW,WAAYA,GAAmB,OAAOA,EAAO,YAAe,WAChF,MAAM,IAAIC,EAAa,wBAAyB,CAAE,OAAQ,QAAS,CAAC,EAEtE,GAAI,OAAOC,GAAmB,SAC5B,MAAM,IAAID,EAAa,wBAAyB,CAAE,OAAQ,gBAAiB,CAAC,EAE9E,GAAIE,IAAkB,IAAA,IAAa,OAAOA,GAAkB,WAC1D,MAAM,IAAIF,EAAa,wBAAyB,CAAE,OAAQ,eAAgB,CAAC,EAE7E,GACEG,IAAsB,IAAA,KACrB,OAAOA,GAAsB,WAC5BA,GACA,OAAOA,EAAkB,sBAAyB,YAEpD,MAAM,IAAIH,EAAa,wBAAyB,CAAE,OAAQ,mBAAoB,CAAC,EAEjF,KAAK,cAAgBI,EAAiBN,EAAQ,cAAe,eAAe,EAC5E,KAAK,gBAAkBO,EAAuBP,EAAQ,eAAe,EACrE,KAAK,kBAAoBK,EACzB,KAAK,UAAY,CACf,eAAgBF,EAAe,QAAQ,QAAS,EAAE,EAClD,SACA,UAAWC,GAAiBI,EAC5B,UAAWC,EACTT,EAAQ,kBAAoB,IAC5B,kBACF,EACA,KAAMA,EAAQ,IAChB,CACF,CAUA,aAAoB,EAAwD,CAC1E,OAAO,KAAK,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AAeR,EAAQH,EAAWQ,CAAI,EAC1DR,CACF,CACF,CAGA,YAAoB,EAAmC,CAGrD,OAFIY,IAAU,IAAA,GAAkBC,EAAgB,KAAK,eAAe,GACpEC,EAAgBF,CAAK,EACdA,EACT,CAGA,WACE,EACA,EACmB,CACnB,IAAMG,EAAMC,EAA2BC,GACjCC,EAAQ,MAAM,QAAQf,CAAM,EAAIA,EAAO,OAAS,EACtD,GAAIe,EAAQ,GAAKA,EAAQH,EACvB,MAAM,IAAI5B,EAAa,sBAAuB,CAAE,SAAQ,QAAO,KAAI,CAAC,EAEtE,OAAOgB,EAAO,KAAK,EAAO,IAAUJ,EAAcJ,EAAO,UAAUwB,EAAM,GAAG,CAAC,CAC/E,CAEA,MAAc,WAAW,EAAqD,CAC5E,MAAO,CACL,SAAUrB,EAAQ,SAClB,IAAK,MAAMsB,EAAatB,EAAQ,MAAO,KAAK,iBAAiB,CAC/D,CACF,CAGA,MAAc,WAAW,EAAkE,CACzF,IAAMuB,EAA+B,CAAC,EACtC,IAAK,IAAMC,KAASxB,EAASuB,EAAS,KAAK,MAAM,KAAK,WAAWC,CAAK,CAAC,EACvE,OAAOD,CACT,CAEA,OACE,EACA,EACA,EAC8B,CAC9B,OAAOE,EAAY,KAAK,UAAWN,EAAQO,EAAKxB,CAAS,CAC3D,CACF,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"identity.js","names":["ACCOUNT","CLIENT_ALIAS","ETH_WITH_0X","assertNoEthZeroXPrefix","value","rest","checksummed","checksumEthereumAddress","GalaSDKError","galaChainUserRef","field","digits","account"],"sources":["../../../src/writes/identity.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { checksumEthereumAddress } from '../utils/eth_address.js';\n\n/** `eth|`, `0x` or nothing, then the 40 hex digits of an Ethereum account. */\nconst ACCOUNT = /^(?:eth\\||0x)?([0-9a-fA-F]{40})$/u;\nconst CLIENT_ALIAS = /^client\\|[A-Za-z0-9_-]+$/u;\n/** `eth|0x...`: not a user reference. An `eth|` reference is followed by the digits alone. */\nconst ETH_WITH_0X = /^eth\\|0[xX](.*)$/su;\n\n/**\n * Refuses `eth|0x...` (any digits, any casing of the `0x`) with `INVALID_ETH_USER_REF_PREFIX`,\n * naming the correct spelling. `eth|0x...` is not an address form: GalaChain's `eth|` reference is\n * followed by the 40 hex digits only. A bare `0x<40 hex>` is a different, normal thing (an\n * Ethereum address) and is not touched. Every place core reads an account refuses it through this\n * one function, before anything is signed or sent.\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` (`params.field` = `field`).\n */\nexport function assertNoEthZeroXPrefix(value: unknown, field: string): void {\n if (typeof value !== 'string') return;\n const rest = ETH_WITH_0X.exec(value)?.[1];\n if (rest === undefined) return;\n const checksummed = /^[0-9a-fA-F]{40}$/u.test(rest) ? checksumEthereumAddress(rest) : undefined;\n throw new GalaSDKError('INVALID_ETH_USER_REF_PREFIX', {\n field,\n value,\n expected: checksummed === undefined ? 'eth|<40 hex digits>' : `eth|${checksummed.slice(2)}`,\n });\n}\n\n/**\n * The GalaChain user reference a read or write names (owner, sender, recipient, lock authority),\n * in the one spelling the gateway receives:\n *\n * - an Ethereum account, as `eth|<40 hex>`, `0x<40 hex>` or bare `<40 hex>`: sent as `eth|` plus\n * its EIP-55 checksummed digits (no `0x`). The gateway refuses every other casing of an `eth|`\n * reference (all lower case, all upper case) with HTTP 400 `DTO_VALIDATION_FAILED`\n * (`IsUserRefConstraint`; recorded in `tests/fixtures/gateway-reads-recorded.json`). A\n * mixed-case spelling whose casing is not the EIP-55 checksum is a typo (what EIP-55 exists to\n * catch) and is refused.\n * - `eth|0x<hex>` is NOT an address form: an `eth|` reference is followed by the digits alone.\n * It is refused before anything is signed or sent (see {@link assertNoEthZeroXPrefix}). A bare\n * `0x<40 hex>` is an ordinary Ethereum address and is converted to `eth|<EIP-55 digits>`.\n * - `client|<id>` (`A-Za-z0-9_-`): a GalaChain alias, kept exactly as written.\n *\n * Anything else is refused before anything is signed or sent (fail closed): an unknown spelling\n * could name an account nobody holds.\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` for `eth|0x...`, otherwise\n * `INVALID_WALLET_ADDRESS` (`params.field` = `field`).\n */\nexport function galaChainUserRef(value: unknown, field: string): string {\n assertNoEthZeroXPrefix(value, field);\n if (typeof value === 'string') {\n if (CLIENT_ALIAS.test(value)) return value;\n const digits = ACCOUNT.exec(value)?.[1];\n const account = digits === undefined ? undefined : checksumEthereumAddress(digits);\n if (account !== undefined) return `eth|${account.slice(2)}`;\n }\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field, value: String(value) });\n}\n"],"mappings":"8HAIA,MAAMA,EAAU,oCACVC,EAAe,4BAEfC,EAAc,qBAWpB,SAAgBC,EAAuB,EAAgB,EAAqB,CAC1E,GAAI,OAAOC,GAAU,SAAU,OAC/B,IAAMC,EAAOH,EAAY,KAAKE,CAAK,CAAC,GAAG,GACvC,GAAIC,IAAS,IAAA,GAAW,OACxB,IAAMC,EAAc,qBAAqB,KAAKD,CAAI,EAAIE,EAAwBF,CAAI,EAAI,IAAA,GACtF,MAAM,IAAIG,EAAa,8BAA+B,CACpD,QACA,QACA,SAAUF,IAAgB,IAAA,GAAY,sBAAwB,OAAOA,EAAY,MAAM,CAAC,GAC1F,CAAC,CACH,CAuBA,SAAgBG,EAAiB,EAAgB,EAAuB,CAEtE,GADAN,EAAuBC,EAAOM,CAAK,EAC/B,OAAON,GAAU,SAAU,CAC7B,GAAIH,EAAa,KAAKG,CAAK,EAAG,OAAOA,EACrC,IAAMO,EAASX,EAAQ,KAAKI,CAAK,CAAC,GAAG,GAC/BQ,EAAUD,IAAW,IAAA,GAAY,IAAA,GAAYJ,EAAwBI,CAAM,EACjF,GAAIC,IAAY,IAAA,GAAW,MAAO,OAAOA,EAAQ,MAAM,CAAC,GAC1D,CACA,MAAM,IAAIJ,EAAa,yBAA0B,CAAE,QAAO,MAAO,OAAOJ,CAAK,CAAE,CAAC,CAClF"}
1
+ {"version":3,"file":"identity.js","names":["ACCOUNT","CLIENT_ALIAS","ETH_WITH_0X","assertNoEthZeroXPrefix","value","rest","checksummed","checksumEthereumAddress","GalaSDKError","galaChainUserRef","field","digits","account"],"sources":["../../../src/writes/identity.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { checksumEthereumAddress } from '../utils/eth_address.js';\n\n/** `eth|`, `0x` or nothing, then the 40 hex digits of an Ethereum account. */\nconst ACCOUNT = /^(?:eth\\||0x)?([0-9a-fA-F]{40})$/u;\nconst CLIENT_ALIAS = /^client\\|[A-Za-z0-9_-]+$/u;\n/** `eth|0x...`: not a user reference. An `eth|` reference is followed by the digits alone. */\nconst ETH_WITH_0X = /^eth\\|0[xX](.*)$/su;\n\n/**\n * Refuses `eth|0x...` (any digits, any casing of the `0x`) with `INVALID_ETH_USER_REF_PREFIX`,\n * naming the correct spelling. `eth|0x...` is not an address form: GalaChain's `eth|` reference is\n * followed by the 40 hex digits only. A bare `0x<40 hex>` is a different, normal thing (an\n * Ethereum address) and is not touched. Every place core reads an account refuses it through this\n * one function, before anything is signed or sent.\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` (`params.field` = `field`).\n */\nexport function assertNoEthZeroXPrefix(value: unknown, field: string): void {\n if (typeof value !== 'string') return;\n const rest = ETH_WITH_0X.exec(value)?.[1];\n if (rest === undefined) return;\n const checksummed = /^[0-9a-fA-F]{40}$/u.test(rest) ? checksumEthereumAddress(rest) : undefined;\n throw new GalaSDKError('INVALID_ETH_USER_REF_PREFIX', {\n field,\n value,\n expected: checksummed === undefined ? 'eth|<40 hex digits>' : `eth|${checksummed.slice(2)}`,\n });\n}\n\n/**\n * The GalaChain user reference a read or write names (owner, sender, recipient, lock authority),\n * in the one spelling the gateway receives:\n *\n * - an Ethereum account, as `eth|<40 hex>`, `0x<40 hex>` or bare `<40 hex>`: sent as `eth|` plus\n * its EIP-55 checksummed digits (no `0x`). The gateway refuses every other casing of an `eth|`\n * reference (all lower case, all upper case) with HTTP 400 `DTO_VALIDATION_FAILED`\n * (`IsUserRefConstraint`; recorded in `tests/fixtures/gateway-reads-recorded.json`). A\n * mixed-case spelling whose casing is not the EIP-55 checksum is a typo (what EIP-55 exists to\n * catch) and is refused.\n * - `eth|0x<hex>` is NOT an address form: an `eth|` reference is followed by the digits alone.\n * It is refused before anything is signed or sent (see {@link assertNoEthZeroXPrefix}). A bare\n * `0x<40 hex>` is an ordinary Ethereum address and is converted to `eth|<EIP-55 digits>`.\n * - `client|<id>` (`A-Za-z0-9_-`): a GalaChain alias, kept exactly as written.\n *\n * Anything else is refused before anything is signed or sent (fail closed): an unknown spelling\n * could name an account nobody holds.\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` for `eth|0x...`, otherwise\n * `INVALID_WALLET_ADDRESS` (`params.field` = `field`).\n */\nexport function galaChainUserRef(value: unknown, field: string): string {\n assertNoEthZeroXPrefix(value, field);\n if (typeof value === 'string') {\n if (CLIENT_ALIAS.test(value)) return value;\n const digits = ACCOUNT.exec(value)?.[1];\n const account = digits === undefined ? undefined : checksumEthereumAddress(digits);\n if (account !== undefined) return `eth|${account.slice(2)}`;\n }\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field, value: String(value) });\n}\n"],"mappings":"A,8HAIA,MAAMA,EAAU,oCACVC,EAAe,4BAEfC,EAAc,qBAWpB,SAAgBC,EAAuB,EAAgB,EAAqB,CAC1E,GAAI,OAAOC,GAAU,SAAU,OAC/B,IAAMC,EAAOH,EAAY,KAAKE,CAAK,CAAC,GAAG,GACvC,GAAIC,IAAS,IAAA,GAAW,OACxB,IAAMC,EAAc,qBAAqB,KAAKD,CAAI,EAAIE,EAAwBF,CAAI,EAAI,IAAA,GACtF,MAAM,IAAIG,EAAa,8BAA+B,CACpD,QACA,QACA,SAAUF,IAAgB,IAAA,GAAY,sBAAwB,OAAOA,EAAY,MAAM,CAAC,GAC1F,CAAC,CACH,CAuBA,SAAgBG,EAAiB,EAAgB,EAAuB,CAEtE,GADAN,EAAuBC,EAAOM,CAAK,EAC/B,OAAON,GAAU,SAAU,CAC7B,GAAIH,EAAa,KAAKG,CAAK,EAAG,OAAOA,EACrC,IAAMO,EAASX,EAAQ,KAAKI,CAAK,CAAC,GAAG,GAC/BQ,EAAUD,IAAW,IAAA,GAAY,IAAA,GAAYJ,EAAwBI,CAAM,EACjF,GAAIC,IAAY,IAAA,GAAW,MAAO,OAAOA,EAAQ,MAAM,CAAC,GAC1D,CACA,MAAM,IAAIJ,EAAa,yBAA0B,CAAE,QAAO,MAAO,OAAOJ,CAAK,CAAE,CAAC,CAClF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"lock.js","names":["lockExpires","value","GalaSDKError","lockName","heldBy","tokens","token","lockTokenDto","owner","expires","name","unlockTokenDto"],"sources":["../../../src/writes/lock.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport type { ResolvedQuantity } from './transfer.js';\n\n/**\n * The `expires` of a lock, or `undefined` to leave it out of the DTO. A non-negative safe integer\n * of epoch milliseconds; `0` is the chain's \"never expires\" and is KEPT in the signed DTO when it\n * is given (a defined field is never dropped), so the signed body is what the caller asked for.\n *\n * @throws GalaSDKError `INVALID_LOCK_EXPIRES`.\n */\nexport function lockExpires(value: unknown): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value;\n // A number is shown as written; anything else by its type (never an object's own text).\n throw new GalaSDKError('INVALID_LOCK_EXPIRES', {\n value: typeof value === 'number' ? String(value) : value === null ? 'null' : typeof value,\n });\n}\n\n/**\n * The `name` of a hold, or `undefined` to leave it out. Any string, `''` included (kept as given).\n *\n * @throws GalaSDKError `INVALID_LOCK_NAME`.\n */\nexport function lockName(value: unknown): string | undefined {\n if (value === undefined || typeof value === 'string') return value;\n throw new GalaSDKError('INVALID_LOCK_NAME', {\n valueType: value === null ? 'null' : typeof value,\n });\n}\n\nfunction heldBy(owner: string, tokens: readonly ResolvedQuantity[]): Record<string, unknown>[] {\n return tokens.map((token) => ({\n owner,\n quantity: token.quantity,\n tokenInstanceKey: token.key,\n }));\n}\n\n/**\n * The unsigned `LockToken` DTO, in the field order the gateway has always received\n * (`lockAuthority, tokenInstances, uniqueKey, expires?, name?`). One lock authority, expiry and\n * name per write: the chain holds every token of the write under the same lock.\n */\nexport function lockTokenDto(\n lockAuthority: string,\n owner: string,\n tokens: readonly ResolvedQuantity[],\n uniqueKey: string,\n expires: number | undefined,\n name: string | undefined,\n): Record<string, unknown> {\n return {\n lockAuthority,\n tokenInstances: heldBy(owner, tokens),\n uniqueKey,\n ...(expires === undefined ? {} : { expires }),\n ...(name === undefined ? {} : { name }),\n };\n}\n\n/** The unsigned `UnlockToken` DTO (`tokenInstances, uniqueKey, name?`). */\nexport function unlockTokenDto(\n owner: string,\n tokens: readonly ResolvedQuantity[],\n uniqueKey: string,\n name: string | undefined,\n): Record<string, unknown> {\n return {\n tokenInstances: heldBy(owner, tokens),\n uniqueKey,\n ...(name === undefined ? {} : { name }),\n };\n}\n"],"mappings":"4DAUA,SAAgBA,EAAY,EAAoC,CAC9D,GAAIC,IAAU,IAAA,GACd,IAAI,OAAOA,GAAU,UAAY,OAAO,cAAcA,CAAK,GAAKA,GAAS,EAAG,OAAOA,EAEnF,MAAM,IAAIC,EAAa,uBAAwB,CAC7C,MAAO,OAAOD,GAAU,SAAW,OAAOA,CAAK,EAAIA,IAAU,KAAO,OAAS,OAAOA,CACtF,CAAC,CAJkF,CAKrF,CAOA,SAAgBE,EAAS,EAAoC,CAC3D,GAAIF,IAAU,IAAA,IAAa,OAAOA,GAAU,SAAU,OAAOA,EAC7D,MAAM,IAAIC,EAAa,oBAAqB,CAC1C,UAAWD,IAAU,KAAO,OAAS,OAAOA,CAC9C,CAAC,CACH,CAEA,SAASG,EAAO,EAAe,EAAgE,CAC7F,OAAOC,EAAO,IAAK,IAAW,CAC5B,QACA,SAAUC,EAAM,SAChB,iBAAkBA,EAAM,GAC1B,EAAE,CACJ,CAOA,SAAgBC,EACd,EACA,EACA,EACA,EACA,EACA,EACyB,CACzB,MAAO,CACL,gBACA,eAAgBH,EAAOI,EAAOH,CAAM,EACpC,YACA,GAAII,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,EAC3C,GAAIC,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,MAAK,CACvC,CACF,CAGA,SAAgBC,EACd,EACA,EACA,EACA,EACyB,CACzB,MAAO,CACL,eAAgBP,EAAOI,EAAOH,CAAM,EACpC,YACA,GAAIK,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,MAAK,CACvC,CACF"}
1
+ {"version":3,"file":"lock.js","names":["lockExpires","value","GalaSDKError","lockName","heldBy","tokens","token","lockTokenDto","owner","expires","name","unlockTokenDto"],"sources":["../../../src/writes/lock.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport type { ResolvedQuantity } from './transfer.js';\n\n/**\n * The `expires` of a lock, or `undefined` to leave it out of the DTO. A non-negative safe integer\n * of epoch milliseconds; `0` is the chain's \"never expires\" and is KEPT in the signed DTO when it\n * is given (a defined field is never dropped), so the signed body is what the caller asked for.\n *\n * @throws GalaSDKError `INVALID_LOCK_EXPIRES`.\n */\nexport function lockExpires(value: unknown): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value;\n // A number is shown as written; anything else by its type (never an object's own text).\n throw new GalaSDKError('INVALID_LOCK_EXPIRES', {\n value: typeof value === 'number' ? String(value) : value === null ? 'null' : typeof value,\n });\n}\n\n/**\n * The `name` of a hold, or `undefined` to leave it out. Any string, `''` included (kept as given).\n *\n * @throws GalaSDKError `INVALID_LOCK_NAME`.\n */\nexport function lockName(value: unknown): string | undefined {\n if (value === undefined || typeof value === 'string') return value;\n throw new GalaSDKError('INVALID_LOCK_NAME', {\n valueType: value === null ? 'null' : typeof value,\n });\n}\n\nfunction heldBy(owner: string, tokens: readonly ResolvedQuantity[]): Record<string, unknown>[] {\n return tokens.map((token) => ({\n owner,\n quantity: token.quantity,\n tokenInstanceKey: token.key,\n }));\n}\n\n/**\n * The unsigned `LockToken` DTO, in the field order the gateway has always received\n * (`lockAuthority, tokenInstances, uniqueKey, expires?, name?`). One lock authority, expiry and\n * name per write: the chain holds every token of the write under the same lock.\n */\nexport function lockTokenDto(\n lockAuthority: string,\n owner: string,\n tokens: readonly ResolvedQuantity[],\n uniqueKey: string,\n expires: number | undefined,\n name: string | undefined,\n): Record<string, unknown> {\n return {\n lockAuthority,\n tokenInstances: heldBy(owner, tokens),\n uniqueKey,\n ...(expires === undefined ? {} : { expires }),\n ...(name === undefined ? {} : { name }),\n };\n}\n\n/** The unsigned `UnlockToken` DTO (`tokenInstances, uniqueKey, name?`). */\nexport function unlockTokenDto(\n owner: string,\n tokens: readonly ResolvedQuantity[],\n uniqueKey: string,\n name: string | undefined,\n): Record<string, unknown> {\n return {\n tokenInstances: heldBy(owner, tokens),\n uniqueKey,\n ...(name === undefined ? {} : { name }),\n };\n}\n"],"mappings":"A,4DAUA,SAAgBA,EAAY,EAAoC,CAC9D,GAAIC,IAAU,IAAA,GACd,IAAI,OAAOA,GAAU,UAAY,OAAO,cAAcA,CAAK,GAAKA,GAAS,EAAG,OAAOA,EAEnF,MAAM,IAAIC,EAAa,uBAAwB,CAC7C,MAAO,OAAOD,GAAU,SAAW,OAAOA,CAAK,EAAIA,IAAU,KAAO,OAAS,OAAOA,CACtF,CAAC,CAJkF,CAKrF,CAOA,SAAgBE,EAAS,EAAoC,CAC3D,GAAIF,IAAU,IAAA,IAAa,OAAOA,GAAU,SAAU,OAAOA,EAC7D,MAAM,IAAIC,EAAa,oBAAqB,CAC1C,UAAWD,IAAU,KAAO,OAAS,OAAOA,CAC9C,CAAC,CACH,CAEA,SAASG,EAAO,EAAe,EAAgE,CAC7F,OAAOC,EAAO,IAAK,IAAW,CAC5B,QACA,SAAUC,EAAM,SAChB,iBAAkBA,EAAM,GAC1B,EAAE,CACJ,CAOA,SAAgBC,EACd,EACA,EACA,EACA,EACA,EACA,EACyB,CACzB,MAAO,CACL,gBACA,eAAgBH,EAAOI,EAAOH,CAAM,EACpC,YACA,GAAII,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,SAAQ,EAC3C,GAAIC,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,MAAK,CACvC,CACF,CAGA,SAAgBC,EACd,EACA,EACA,EACA,EACyB,CACzB,MAAO,CACL,eAAgBP,EAAOI,EAAOH,CAAM,EACpC,YACA,GAAIK,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,MAAK,CACvC,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{GalaSDKError as e,isGalaError as t}from"../classes/gala_sdk_error.js";import{serialize as n}from"../utils/signing.js";import{signPreSend as r}from"../utils/pre_send.js";import{buildRequestHeaders as i,readBlockNumberHeader as a,readHeader as o,readResponseBody as s,requestWithTimeout as c}from"../utils/transport.js";const l=/* @__PURE__ */ new Set([`signature`,`prefix`,`types`,`domain`]);function u(e,t){if(typeof t.signature!=`string`)return!1;let r=Object.fromEntries(Object.entries(t).filter(([e])=>!l.has(e)));return n(r)===e}async function d(t,i,a){let o=n(a),s=await r(t,i,a),c;try{c=u(o,s)?JSON.stringify(s):void 0}catch(t){throw new e(`SIGNING_FAILED`,{method:i,reason:`failed`},{cause:t})}if(c===void 0)throw new e(`SIGNING_FAILED`,{method:i,reason:`failed`});return c}async function f(n,r,a,o,l){let u=(t,n)=>new e(`GATEWAY_WRITE_OUTCOME_UNKNOWN`,{method:r,reason:t},{url:a,uniqueKey:l,cause:n}),d;try{d=await c(n.requestor,a,{method:`POST`,headers:i(n.wire,{json:!0}),body:o},n.timeoutMs)}catch(e){throw t(e,`REQUEST_TIMEOUT`)?u(`timeout`,e):t(e,`TRANSPORT_ERROR`)?u(`transport`,e):e}try{return{response:d,body:await s(d)}}catch(e){throw u(`transport`,e)}}function p(e){if(typeof e!=`string`)return;let t=e.trim();return t===``?void 0:t}function m(e,t){let n=e?.[t];return typeof n==`string`?n:``}function h(t,n,r,i,s){let c={status:i.status,body:s,url:r,uniqueKey:n},l=typeof s==`object`&&s&&!Array.isArray(s)?s:void 0,u=l?.Status;if(typeof u==`number`&&u!==1)throw new e(`GATEWAY_WRITE_REJECTED`,{method:t,chainStatus:u,errorKey:m(l,`ErrorKey`),serverMessage:m(l,`Message`)},c);if(!i.ok)throw new e(`GATEWAY_HTTP_ERROR`,{method:t,status:i.status,serverMessage:m(l,`Message`)||m(l,`message`)},c);let d=p(o(i,`x-transaction-id`))??p(l?.transactionId);if(l===void 0||!(u===1||u===void 0&&d!==void 0))throw new e(`GATEWAY_RESPONSE_INVALID`,{method:t},c);return{method:t,uniqueKey:n,transactionId:d,blockNumber:a(i),data:l.Data,body:s}}async function g(e,t,n,r){let i=await d(e.signer,t,n),a=`${e.gatewayBaseUrl}/api/asset/token-contract/${t}`,{response:o,body:s}=await f(e,t,a,i,r);return h(t,r,a,o,s)}export{g as submitWrite};
1
+ import{GalaSDKError as e,isGalaError as t}from"../classes/gala_sdk_error.js";import{serialize as n}from"../utils/signing.js";import{withDtoOperation as r}from"../utils/dto_operation.js";import{signPreSend as i}from"../utils/pre_send.js";import{buildRequestHeaders as a,readBlockNumberHeader as o,readHeader as s,readResponseBody as c,requestWithTimeout as l}from"../utils/transport.js";const u=`asset/token-contract`,d=/* @__PURE__ */ new Set([`signature`,`prefix`,`types`,`domain`]);function f(e,t){if(typeof t.signature!=`string`)return!1;let r=Object.fromEntries(Object.entries(t).filter(([e])=>!d.has(e)));return n(r)===e}async function p(t,a,o){let s=r(u,a,o),c=n(s),l=await i(t,u,a,s),d;try{d=f(c,l)?JSON.stringify(l):void 0}catch(t){throw new e(`SIGNING_FAILED`,{method:a,reason:`failed`},{cause:t})}if(d===void 0)throw new e(`SIGNING_FAILED`,{method:a,reason:`failed`});return d}async function m(n,r,i,o,s){let u=(t,n)=>new e(`GATEWAY_WRITE_OUTCOME_UNKNOWN`,{method:r,reason:t},{url:i,uniqueKey:s,cause:n}),d;try{d=await l(n.requestor,i,{method:`POST`,headers:a(n.wire,{json:!0}),body:o},n.timeoutMs)}catch(e){throw t(e,`REQUEST_TIMEOUT`)?u(`timeout`,e):t(e,`TRANSPORT_ERROR`)?u(`transport`,e):e}try{return{response:d,body:await c(d)}}catch(e){throw u(`transport`,e)}}function h(e){if(typeof e!=`string`)return;let t=e.trim();return t===``?void 0:t}function g(e,t){let n=e?.[t];return typeof n==`string`?n:``}function _(t,n,r,i,a){let c={status:i.status,body:a,url:r,uniqueKey:n},l=typeof a==`object`&&a&&!Array.isArray(a)?a:void 0,u=l?.Status;if(typeof u==`number`&&u!==1)throw new e(`GATEWAY_WRITE_REJECTED`,{method:t,chainStatus:u,errorKey:g(l,`ErrorKey`),serverMessage:g(l,`Message`)},c);if(!i.ok)throw new e(`GATEWAY_HTTP_ERROR`,{method:t,status:i.status,serverMessage:g(l,`Message`)||g(l,`message`)},c);let d=h(s(i,`x-transaction-id`))??h(l?.transactionId);if(l===void 0||!(u===1||u===void 0&&d!==void 0))throw new e(`GATEWAY_RESPONSE_INVALID`,{method:t},c);return{method:t,uniqueKey:n,transactionId:d,blockNumber:o(i),data:l.Data,body:a}}async function v(e,t,n,r){let i=await p(e.signer,t,n),a=`${e.gatewayBaseUrl}/api/${u}/${t}`,{response:o,body:s}=await m(e,t,a,i,r);return _(t,r,a,o,s)}export{v as submitWrite};
2
2
  //# sourceMappingURL=submit.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"submit.js","names":["SIGNATURE_ENVELOPE","carriesExactlyTheDto","signed","\"signature\"","withoutEnvelope","key","serialize","builtDto","signedPayload","dto","signPreSend","signer","method","payload","cause","GalaSDKError","post","outcomeUnknown","response","requestWithTimeout","transport","url","buildRequestHeaders","error","isGalaError","readResponseBody","nonEmptyString","value","trimmed","stringField","record","receiptOf","context","envelope","body","chainStatus","\"Status\"","transactionId","readHeader","\"transactionId\"","readBlockNumberHeader","\"Data\"","submitWrite","uniqueKey"],"sources":["../../../src/writes/submit.ts"],"sourcesContent":["import { GalaSDKError, isGalaError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport type { GalaChainSigner } from '../classes/signers.js';\nimport type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { signPreSend } from '../utils/pre_send.js';\nimport { serialize } from '../utils/signing.js';\nimport {\n buildRequestHeaders,\n readBlockNumberHeader,\n readHeader,\n readResponseBody,\n requestWithTimeout,\n} from '../utils/transport.js';\nimport type { GatewayWriteMethod, GatewayWriteReceipt } from './types.js';\n\n/** What every write is sent with. */\nexport interface WriteTransport {\n readonly gatewayBaseUrl: string;\n readonly signer: GalaChainSigner;\n readonly requestor: HttpRequestor;\n readonly timeoutMs: number;\n readonly wire: WireOptions | undefined;\n}\n\n/**\n * The fields a signer may add next to the DTO: the signature and, for the wallet schemes, the\n * personal-sign `prefix` and the EIP-712 `types` / `domain`. Nothing else: a signer that inserts a\n * signer hint (`signerAddress`, `signerPublicKey`) would make the chain attribute the write to\n * whoever that names (the phantom-signer class), so such a body is never sent.\n */\nconst SIGNATURE_ENVELOPE = new Set(['signature', 'prefix', 'types', 'domain']);\n\n/**\n * True when `signed` is the DTO the SDK built plus signature-envelope fields only: without the\n * envelope it serializes (the chain's own serialization) exactly as the DTO did BEFORE it was\n * handed to the signer, so a field the signer added, dropped or changed (also by mutating the\n * object it was handed) is caught; and its signature is a string.\n */\nfunction carriesExactlyTheDto(builtDto: string, signed: Record<string, unknown>): boolean {\n if (typeof signed['signature'] !== 'string') return false;\n const withoutEnvelope = Object.fromEntries(\n Object.entries(signed).filter(([key]) => !SIGNATURE_ENVELOPE.has(key)),\n );\n return serialize(withoutEnvelope) === builtDto;\n}\n\n/**\n * Signs `dto` and serializes the body to send, all before anything leaves: a signer failure, a\n * signer that changed the DTO or added a field to it, and a body that cannot be serialized are all\n * `SIGNING_FAILED` (pre-send: nothing was transmitted, a retry is safe).\n */\nasync function signedPayload(\n signer: GalaChainSigner,\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n): Promise<string> {\n // Taken before the signer sees the DTO: what it hands back is compared with this, not with an\n // object it could have mutated.\n const builtDto = serialize(dto);\n const signed = await signPreSend(signer, method, dto);\n let payload: string | undefined;\n try {\n payload = carriesExactlyTheDto(builtDto, signed) ? JSON.stringify(signed) : undefined;\n } catch (cause: unknown) {\n // A value JSON cannot carry (a BigInt, a cycle) in what the signer returned.\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause });\n }\n if (payload === undefined) {\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' });\n }\n return payload;\n}\n\n/**\n * POSTs the signed body. Neither a timeout nor a transport failure proves the write was not\n * applied, so both are `GATEWAY_WRITE_OUTCOME_UNKNOWN` carrying the write's `uniqueKey` (the only\n * handle to check it with), never a retryable read failure. Any other rejection is the app's\n * requestor's own and reaches the caller unchanged.\n */\nasync function post(\n transport: WriteTransport,\n method: GatewayWriteMethod,\n url: string,\n payload: string,\n uniqueKey: string,\n): Promise<{ response: HTTPResponse; body: unknown }> {\n const outcomeUnknown = (\n reason: 'timeout' | 'transport',\n cause: unknown,\n ): GalaSDKError<'GATEWAY_WRITE_OUTCOME_UNKNOWN'> =>\n new GalaSDKError(\n 'GATEWAY_WRITE_OUTCOME_UNKNOWN',\n { method, reason },\n { url, uniqueKey, cause },\n );\n let response: HTTPResponse;\n try {\n response = await requestWithTimeout(\n transport.requestor,\n url,\n {\n method: 'POST',\n headers: buildRequestHeaders(transport.wire, { json: true }),\n body: payload,\n },\n transport.timeoutMs,\n );\n } catch (error: unknown) {\n if (isGalaError(error, 'REQUEST_TIMEOUT')) throw outcomeUnknown('timeout', error);\n if (isGalaError(error, 'TRANSPORT_ERROR')) throw outcomeUnknown('transport', error);\n throw error;\n }\n try {\n return { response, body: await readResponseBody(response) };\n } catch (cause: unknown) {\n // The answer's headers arrived and its body broke off: what the gateway did is unknown.\n throw outcomeUnknown('transport', cause);\n }\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\nfunction stringField(record: Record<string, unknown> | undefined, key: string): string {\n const value = record?.[key];\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * Reads the gateway's answer to a write. GalaChain's `Status` is checked BEFORE any transaction id\n * is trusted (a proxy can set `x-transaction-id` whatever the chain did):\n *\n * - a numeric `Status` other than 1, in any HTTP status: `GATEWAY_WRITE_REJECTED` (the chain refused);\n * - any other non-2xx: `GATEWAY_HTTP_ERROR`;\n * - a 2xx that is not a JSON object, has a non-numeric `Status`, or has no `Status` AND names no\n * transaction id: `GATEWAY_RESPONSE_INVALID` (it proves nothing; the write may have been applied);\n * - `Status: 1`, or no `Status` with a transaction id: the receipt.\n *\n * Every error carries the HTTP status, the body, the URL and the write's `uniqueKey`.\n */\nfunction receiptOf(\n method: GatewayWriteMethod,\n uniqueKey: string,\n url: string,\n response: HTTPResponse,\n body: unknown,\n): GatewayWriteReceipt {\n const context: GalaErrorContext = { status: response.status, body, url, uniqueKey };\n const envelope =\n typeof body === 'object' && body !== null && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n const chainStatus = envelope?.['Status'];\n if (typeof chainStatus === 'number' && chainStatus !== 1) {\n throw new GalaSDKError(\n 'GATEWAY_WRITE_REJECTED',\n {\n method,\n chainStatus,\n errorKey: stringField(envelope, 'ErrorKey'),\n serverMessage: stringField(envelope, 'Message'),\n },\n context,\n );\n }\n if (!response.ok) {\n throw new GalaSDKError(\n 'GATEWAY_HTTP_ERROR',\n {\n method,\n status: response.status,\n serverMessage: stringField(envelope, 'Message') || stringField(envelope, 'message'),\n },\n context,\n );\n }\n const transactionId =\n nonEmptyString(readHeader(response, 'x-transaction-id')) ??\n nonEmptyString(envelope?.['transactionId']);\n const accepted = chainStatus === 1 || (chainStatus === undefined && transactionId !== undefined);\n if (envelope === undefined || !accepted) {\n throw new GalaSDKError('GATEWAY_RESPONSE_INVALID', { method }, context);\n }\n return {\n method,\n uniqueKey,\n transactionId,\n blockNumber: readBlockNumberHeader(response),\n data: envelope['Data'],\n body,\n };\n}\n\n/**\n * Signs `dto` for `method`, POSTs it to `<gatewayBaseUrl>/api/asset/token-contract/<method>` and\n * reads the answer (see {@link receiptOf}). The body sent is exactly what the signer returned: the\n * DTO plus its signature (and, for a wallet scheme, `prefix` / `types` / `domain`).\n */\nexport async function submitWrite(\n transport: WriteTransport,\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n uniqueKey: string,\n): Promise<GatewayWriteReceipt> {\n const payload = await signedPayload(transport.signer, method, dto);\n const url = `${transport.gatewayBaseUrl}/api/asset/token-contract/${method}`;\n const { response, body } = await post(transport, method, url, payload, uniqueKey);\n return receiptOf(method, uniqueKey, url, response, body);\n}\n"],"mappings":"qUA8BA,MAAMA,kBAAqB,IAAI,IAAI,CAAC,YAAa,SAAU,QAAS,QAAQ,CAAC,EAQ7E,SAASC,EAAqB,EAAkB,EAA0C,CACxF,GAAI,OAAOC,EAAOC,WAAiB,SAAU,MAAO,GACpD,IAAMC,EAAkB,OAAO,YAC7B,OAAO,QAAQF,CAAM,CAAC,CAAC,QAAQ,CAACG,KAAS,CAACL,EAAmB,IAAIK,CAAG,CAAC,CACvE,EACA,OAAOC,EAAUF,CAAe,IAAMG,CACxC,CAOA,eAAeC,EACb,EACA,EACA,EACiB,CAGjB,IAAMD,EAAWD,EAAUG,CAAG,EACxBP,EAAS,MAAMQ,EAAYC,EAAQC,EAAQH,CAAG,EAChDI,EACJ,GAAI,CACF,EAAUZ,EAAqBM,EAAUL,CAAM,EAAI,KAAK,UAAUA,CAAM,EAAI,IAAA,EAC9E,OAASY,EAAgB,CAEvB,MAAM,IAAIC,EAAa,iBAAkB,CAAE,SAAQ,OAAQ,QAAS,EAAG,CAAE,OAAM,CAAC,CAClF,CACA,GAAIF,IAAY,IAAA,G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EAAYI,EAAU,UAAU,EAC1C,cAAeJ,EAAYI,EAAU,SAAS,CAChD,EACAD,CACF,EAEF,GAAI,CAACd,EAAS,GACZ,MAAM,IAAIH,EACR,qBACA,CACE,SACA,OAAQG,EAAS,OACjB,cAAeW,EAAYI,EAAU,SAAS,GAAKJ,EAAYI,EAAU,SAAS,CACpF,EACAD,CACF,EAEF,IAAMK,EACJX,EAAeY,EAAWpB,EAAU,kBAAkB,CAAC,GACvDQ,EAAeO,GAAWM,aAAgB,EAE5C,GAAIN,IAAa,IAAA,IAAa,EADbE,IAAgB,GAAMA,IAAgB,IAAA,IAAaE,IAAkB,IAAA,IAEpF,MAAM,IAAItB,EAAa,2BAA4B,CAAE,QAAO,EAAGiB,CAAO,EAExE,MAAO,CACL,SACA,YACA,gBACA,YAAaQ,EAAsBtB,CAAQ,EAC3C,KAAMe,EAASQ,KACf,MACF,CACF,CAOA,eAAsBC,EACpB,EACA,EACA,EACA,EAC8B,CAC9B,IAAM7B,EAAU,MAAML,EAAcY,EAAU,OAAQR,EAAQH,CAAG,EAC3DY,EAAM,GAAGD,EAAU,eAAe,4BAA4BR,IAC9D,CAAE,WAAU,QAAS,MAAMI,EAAKI,EAAWR,EAAQS,EAAKR,EAAS8B,CAAS,EAChF,OAAOZ,EAAUnB,EAAQ+B,EAAWtB,EAAKH,EAAUgB,CAAI,CACzD"}
1
+ {"version":3,"file":"submit.js","names":["TOKEN_CONTRACT","SIGNATURE_ENVELOPE","carriesExactlyTheDto","signed","\"signature\"","withoutEnvelope","key","serialize","builtDto","signedPayload","operated","withDtoOperation","method","dto","signPreSend","signer","payload","cause","GalaSDKError","post","outcomeUnknown","response","requestWithTimeout","transport","url","buildRequestHeaders","error","isGalaError","readResponseBody","nonEmptyString","value","trimmed","stringField","record","receiptOf","context","envelope","body","chainStatus","\"Status\"","transactionId","readHeader","\"transactionId\"","readBlockNumberHeader","\"Data\"","submitWrite","uniqueKey"],"sources":["../../../src/writes/submit.ts"],"sourcesContent":["import { GalaSDKError, isGalaError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport type { GalaChainSigner } from '../classes/signers.js';\nimport type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { withDtoOperation } from '../utils/dto_operation.js';\nimport { signPreSend } from '../utils/pre_send.js';\nimport { serialize } from '../utils/signing.js';\nimport {\n buildRequestHeaders,\n readBlockNumberHeader,\n readHeader,\n readResponseBody,\n requestWithTimeout,\n} from '../utils/transport.js';\nimport type { GatewayWriteMethod, GatewayWriteReceipt } from './types.js';\n\n/** The contract every write of this module is sent to (its URL path and its `dtoOperation`). */\nconst TOKEN_CONTRACT = 'asset/token-contract';\n\n/** What every write is sent with. */\nexport interface WriteTransport {\n readonly gatewayBaseUrl: string;\n readonly signer: GalaChainSigner;\n readonly requestor: HttpRequestor;\n readonly timeoutMs: number;\n readonly wire: WireOptions | undefined;\n}\n\n/**\n * The fields a signer may add next to the DTO: the signature and, for the wallet schemes, the\n * personal-sign `prefix` and the EIP-712 `types` / `domain`. Nothing else: a signer that inserts a\n * signer hint (`signerAddress`, `signerPublicKey`) would make the chain attribute the write to\n * whoever that names (the phantom-signer class), so such a body is never sent.\n */\nconst SIGNATURE_ENVELOPE = new Set(['signature', 'prefix', 'types', 'domain']);\n\n/**\n * True when `signed` is the DTO the SDK built plus signature-envelope fields only: without the\n * envelope it serializes (the chain's own serialization) exactly as the DTO did BEFORE it was\n * handed to the signer, so a field the signer added, dropped or changed (also by mutating the\n * object it was handed) is caught; and its signature is a string.\n */\nfunction carriesExactlyTheDto(builtDto: string, signed: Record<string, unknown>): boolean {\n if (typeof signed['signature'] !== 'string') return false;\n const withoutEnvelope = Object.fromEntries(\n Object.entries(signed).filter(([key]) => !SIGNATURE_ENVELOPE.has(key)),\n );\n return serialize(withoutEnvelope) === builtDto;\n}\n\n/**\n * Signs `dto` and serializes the body to send, all before anything leaves: a signer failure, a\n * signer that changed the DTO or added a field to it, and a body that cannot be serialized are all\n * `SIGNING_FAILED` (pre-send: nothing was transmitted, a retry is safe).\n */\nasync function signedPayload(\n signer: GalaChainSigner,\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n): Promise<string> {\n // Taken before the signer sees the DTO: what it hands back is compared with this, not with an\n // object it could have mutated.\n const operated = withDtoOperation(TOKEN_CONTRACT, method, dto);\n const builtDto = serialize(operated);\n const signed = await signPreSend(signer, TOKEN_CONTRACT, method, operated);\n let payload: string | undefined;\n try {\n payload = carriesExactlyTheDto(builtDto, signed) ? JSON.stringify(signed) : undefined;\n } catch (cause: unknown) {\n // A value JSON cannot carry (a BigInt, a cycle) in what the signer returned.\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause });\n }\n if (payload === undefined) {\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' });\n }\n return payload;\n}\n\n/**\n * POSTs the signed body. Neither a timeout nor a transport failure proves the write was not\n * applied, so both are `GATEWAY_WRITE_OUTCOME_UNKNOWN` carrying the write's `uniqueKey` (the only\n * handle to check it with), never a retryable read failure. Any other rejection is the app's\n * requestor's own and reaches the caller unchanged.\n */\nasync function post(\n transport: WriteTransport,\n method: GatewayWriteMethod,\n url: string,\n payload: string,\n uniqueKey: string,\n): Promise<{ response: HTTPResponse; body: unknown }> {\n const outcomeUnknown = (\n reason: 'timeout' | 'transport',\n cause: unknown,\n ): GalaSDKError<'GATEWAY_WRITE_OUTCOME_UNKNOWN'> =>\n new GalaSDKError(\n 'GATEWAY_WRITE_OUTCOME_UNKNOWN',\n { method, reason },\n { url, uniqueKey, cause },\n );\n let response: HTTPResponse;\n try {\n response = await requestWithTimeout(\n transport.requestor,\n url,\n {\n method: 'POST',\n headers: buildRequestHeaders(transport.wire, { json: true }),\n body: payload,\n },\n transport.timeoutMs,\n );\n } catch (error: unknown) {\n if (isGalaError(error, 'REQUEST_TIMEOUT')) throw outcomeUnknown('timeout', error);\n if (isGalaError(error, 'TRANSPORT_ERROR')) throw outcomeUnknown('transport', error);\n throw error;\n }\n try {\n return { response, body: await readResponseBody(response) };\n } catch (cause: unknown) {\n // The answer's headers arrived and its body broke off: what the gateway did is unknown.\n throw outcomeUnknown('transport', cause);\n }\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\nfunction stringField(record: Record<string, unknown> | undefined, key: string): string {\n const value = record?.[key];\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * Reads the gateway's answer to a write. GalaChain's `Status` is checked BEFORE any transaction id\n * is trusted (a proxy can set `x-transaction-id` whatever the chain did):\n *\n * - a numeric `Status` other than 1, in any HTTP status: `GATEWAY_WRITE_REJECTED` (the chain refused);\n * - any other non-2xx: `GATEWAY_HTTP_ERROR`;\n * - a 2xx that is not a JSON object, has a non-numeric `Status`, or has no `Status` AND names no\n * transaction id: `GATEWAY_RESPONSE_INVALID` (it proves nothing; the write may have been applied);\n * - `Status: 1`, or no `Status` with a transaction id: the receipt.\n *\n * Every error carries the HTTP status, the body, the URL and the write's `uniqueKey`.\n */\nfunction receiptOf(\n method: GatewayWriteMethod,\n uniqueKey: string,\n url: string,\n response: HTTPResponse,\n body: unknown,\n): GatewayWriteReceipt {\n const context: GalaErrorContext = { status: response.status, body, url, uniqueKey };\n const envelope =\n typeof body === 'object' && body !== null && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n const chainStatus = envelope?.['Status'];\n if (typeof chainStatus === 'number' && chainStatus !== 1) {\n throw new GalaSDKError(\n 'GATEWAY_WRITE_REJECTED',\n {\n method,\n chainStatus,\n errorKey: stringField(envelope, 'ErrorKey'),\n serverMessage: stringField(envelope, 'Message'),\n },\n context,\n );\n }\n if (!response.ok) {\n throw new GalaSDKError(\n 'GATEWAY_HTTP_ERROR',\n {\n method,\n status: response.status,\n serverMessage: stringField(envelope, 'Message') || stringField(envelope, 'message'),\n },\n context,\n );\n }\n const transactionId =\n nonEmptyString(readHeader(response, 'x-transaction-id')) ??\n nonEmptyString(envelope?.['transactionId']);\n const accepted = chainStatus === 1 || (chainStatus === undefined && transactionId !== undefined);\n if (envelope === undefined || !accepted) {\n throw new GalaSDKError('GATEWAY_RESPONSE_INVALID', { method }, context);\n }\n return {\n method,\n uniqueKey,\n transactionId,\n blockNumber: readBlockNumberHeader(response),\n data: envelope['Data'],\n body,\n };\n}\n\n/**\n * Signs `dto` for `method`, POSTs it to `<gatewayBaseUrl>/api/asset/token-contract/<method>` and\n * reads the answer (see {@link receiptOf}). The body sent is exactly what the signer returned: the\n * DTO plus its signature (and, for a wallet scheme, `prefix` / `types` / `domain`).\n */\nexport async function submitWrite(\n transport: WriteTransport,\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n uniqueKey: string,\n): Promise<GatewayWriteReceipt> {\n const payload = await signedPayload(transport.signer, method, dto);\n const url = `${transport.gatewayBaseUrl}/api/${TOKEN_CONTRACT}/${method}`;\n const { response, body } = await post(transport, method, url, payload, uniqueKey);\n return receiptOf(method, uniqueKey, url, response, body);\n}\n"],"mappings":"A,kYAiBA,MAAMA,EAAiB,uBAiBjBC,kBAAqB,IAAI,IAAI,CAAC,YAAa,SAAU,QAAS,QAAQ,CAAC,EAQ7E,SAASC,EAAqB,EAAkB,EAA0C,CACxF,GAAI,OAAOC,EAAOC,WAAiB,SAAU,MAAO,GACpD,IAAMC,EAAkB,OAAO,YAC7B,OAAO,QAAQF,CAAM,CAAC,CAAC,QAAQ,CAACG,KAAS,CAACL,EAAmB,IAAIK,CAAG,CAAC,CACvE,EACA,OAAOC,EAAUF,CAAe,IAAMG,CACxC,CAOA,eAAeC,EACb,EACA,EACA,EACiB,CAGjB,IAAMC,EAAWC,EAAiBX,EAAgBY,EAAQC,CAAG,EACvDL,EAAWD,EAAUG,CAAQ,EAC7BP,EAAS,MAAMW,EAAYC,EAAQf,EAAgBY,EAAQF,CAAQ,EACrEM,EACJ,GAAI,CACF,EAAUd,EAAqBM,EAAUL,CA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AAS,UAAYA,GAAiB,CAAC,MAAM,QAAQA,CAAI,EAC3DA,EACD,IAAA,GACAC,EAAcF,GAAWG,OAC/B,GAAI,OAAOD,GAAgB,UAAYA,IAAgB,EACrD,MAAM,IAAIpB,EACR,yBACA,CACE,SACA,cACA,SAAUc,EAAYI,EAAU,UAAU,EAC1C,cAAeJ,EAAYI,EAAU,SAAS,CAChD,EACAD,CACF,EAEF,GAAI,CAACd,EAAS,GACZ,MAAM,IAAIH,EACR,qBACA,CACE,SACA,OAAQG,EAAS,OACjB,cAAeW,EAAYI,EAAU,SAAS,GAAKJ,EAAYI,EAAU,SAAS,CACpF,EACAD,CACF,EAEF,IAAMK,EACJX,EAAeY,EAAWpB,EAAU,kBAAkB,CAAC,GACvDQ,EAAeO,GAAWM,aAAgB,EAE5C,GAAIN,IAAa,IAAA,IAAa,EADbE,IAAgB,GAAMA,IAAgB,IAAA,IAAaE,IAAkB,IAAA,IAEpF,MAAM,IAAItB,EAAa,2BAA4B,CAAE,QAAO,EAAGiB,CAAO,EAExE,MAAO,CACL,SACA,YACA,gBACA,YAAaQ,EAAsBtB,CAAQ,EAC3C,KAAMe,EAASQ,KACf,MACF,CACF,CAOA,eAAsBC,EACpB,EACA,EACA,EACA,EAC8B,CAC9B,IAAM7B,EAAU,MAAMP,EAAcc,EAAU,OAAQX,EAAQC,CAAG,EAC3DW,EAAM,GAAGD,EAAU,eAAe,OAAOvB,EAAe,GAAGY,IAC3D,CAAE,WAAU,QAAS,MAAMO,EAAKI,EAAWX,EAAQY,EAAKR,EAAS8B,CAAS,EAChF,OAAOZ,EAAUtB,EAAQkC,EAAWtB,EAAKH,EAAUgB,CAAI,CACzD,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"token_ref.js","names":["BigNumber","DECIMAL","INSTANCE","writeQuantity","value","GalaSDKError","classKeyOf","splitClassKey","tryParseTokenClassKey","invalidReference","tokenClassKeyOf","field","key","instanceKey","checkQuantity","input","at","checkToken","tokenName","tokenClassKey","instance","chosen","resolveToken","token","resolver","resolved","byInstance","cause","isGalaError","record"],"sources":["../../../src/writes/token_ref.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport { splitClassKey, tryParseTokenClassKey } from '../utils/class_key.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { GalaChainTokenInstanceKey, TokenNameResolver, TokenQuantityInput } from './types.js';\n\n/** A plain decimal: digits, optionally a fraction. No sign, exponent, hex, spaces or separators. */\nconst DECIMAL = /^[0-9]+(?:\\.[0-9]+)?$/u;\nconst INSTANCE = /^[0-9]+$/u;\n\n/**\n * The quantity of a write, exactly as the caller wrote it: whole tokens as a plain decimal string\n * greater than zero. It is returned unchanged (never scaled to base units, never re-formatted), so\n * the signed amount is the amount the caller passed. A JS number is refused: it may already have\n * lost digits (`0.1 + 0.2`), and the chain receives strings.\n *\n * @throws GalaSDKError `INVALID_QUANTITY`.\n */\nexport function writeQuantity(value: unknown, field: string): string {\n if (typeof value === 'string' && DECIMAL.test(value) && new BigNumber(value).isGreaterThan(0)) {\n return value;\n }\n throw new GalaSDKError('INVALID_QUANTITY', { field, value: String(value) });\n}\n\n/**\n * The class key a write input names, or `undefined` when it is not one. Stricter than\n * `tryParseTokenClassKey` for the pipe form: `a|b|c|d|e` is refused rather than read as collection\n * `a|b`, because a five-part pipe string is someone's `class key|instance`, and signing a transfer\n * of a different collection is the one outcome a write must never have.\n */\nfunction classKeyOf(value: unknown): GalaChainTokenClassKey | undefined {\n if (typeof value !== 'string') return tryParseTokenClassKey(value);\n if (!value.includes('|')) return splitClassKey(value, '$');\n const parts = value.split('|');\n return parts.length === 4 ? splitClassKey(value, '|') : undefined;\n}\n\nfunction invalidReference(\n field: string,\n reason: 'missing' | 'ambiguous' | 'bad_class_key' | 'bad_instance',\n): GalaSDKError<'INVALID_TOKEN_REFERENCE'> {\n return new GalaSDKError('INVALID_TOKEN_REFERENCE', { field, reason });\n}\n\n/**\n * The class key `value` names, in the forms a write accepts (see {@link classKeyOf}), as the four\n * parts and nothing else; the gateway reads take their keys this way too.\n *\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`missing` for `undefined`, else `bad_class_key`).\n */\nexport function tokenClassKeyOf(value: unknown, field: string): GalaChainTokenClassKey {\n if (value === undefined) throw invalidReference(field, 'missing');\n const key = classKeyOf(value);\n if (key === undefined) throw invalidReference(field, 'bad_class_key');\n return {\n collection: key.collection,\n category: key.category,\n type: key.type,\n additionalKey: key.additionalKey,\n };\n}\n\n/** The fields of an instance key, and only those, in the order the chain DTOs carry them. */\nfunction instanceKey(key: GalaChainTokenClassKey, instance: string): GalaChainTokenInstanceKey {\n return {\n collection: key.collection,\n category: key.category,\n type: key.type,\n additionalKey: key.additionalKey,\n instance,\n };\n}\n\n/** A token named either way, checked synchronously; a name is resolved later (see {@link resolveToken}). */\nexport type CheckedToken =\n | { readonly kind: 'key'; readonly key: GalaChainTokenInstanceKey }\n | { readonly kind: 'name'; readonly tokenName: string };\n\n/** One checked token-and-quantity of a write. */\nexport interface CheckedQuantity {\n readonly quantity: string;\n readonly token: CheckedToken;\n}\n\n/**\n * Checks one token-and-quantity input: the quantity as `<at>quantity`, the token as `<at>token`\n * (`at` is `''` for a transfer, `tokens[2].` for a batch entry).\n *\n * @throws GalaSDKError `INVALID_QUANTITY`, `INVALID_TOKEN_REFERENCE`.\n */\nexport function checkQuantity(input: TokenQuantityInput, at: string): CheckedQuantity {\n return {\n quantity: writeQuantity(input.quantity, `${at}quantity`),\n token: checkToken(input, `${at}token`),\n };\n}\n\n/**\n * Checks how a write input names its token, without resolving a name (so invalid input never\n * costs a resolver round trip).\n *\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE`.\n */\nexport function checkToken(input: TokenQuantityInput, field: string): CheckedToken {\n const { tokenClassKey, tokenName, instance } = input;\n if (tokenName !== undefined) {\n if (tokenClassKey !== undefined || instance !== undefined) {\n throw invalidReference(field, 'ambiguous');\n }\n if (typeof tokenName !== 'string' || tokenName === '') throw invalidReference(field, 'missing');\n return { kind: 'name', tokenName };\n }\n const key = tokenClassKeyOf(tokenClassKey, field);\n const chosen: unknown = instance ?? '0';\n if (typeof chosen !== 'string' || !INSTANCE.test(chosen)) {\n throw invalidReference(field, 'bad_instance');\n }\n return { kind: 'key', key: instanceKey(key, chosen) };\n}\n\n/**\n * The instance key a checked token stands for. A name goes through the app's resolver at the\n * boundary of \"nothing was sent\": a rejection becomes `TOKEN_NAME_RESOLUTION_FAILED` (the\n * original as `cause`), an SDK error passes through, and an answer that is not a key is a failed\n * resolution too, so an unusable answer is never signed.\n *\n * @throws GalaSDKError `NO_TOKEN_NAME_RESOLVER`, `TOKEN_NAME_RESOLUTION_FAILED`.\n */\nexport async function resolveToken(\n token: CheckedToken,\n resolver: TokenNameResolver | undefined,\n): Promise<GalaChainTokenInstanceKey> {\n if (token.kind === 'key') return token.key;\n const { tokenName } = token;\n if (resolver === undefined) throw new GalaSDKError('NO_TOKEN_NAME_RESOLVER', { tokenName });\n let resolved: unknown;\n // Decided once, before the await: which answer shape is expected cannot change mid-call.\n let byInstance = false;\n try {\n if (resolver.resolveTokenInstance !== undefined) {\n byInstance = true;\n resolved = await resolver.resolveTokenInstance(tokenName);\n } else {\n resolved = await resolver.resolveTokenClassKey(tokenName);\n }\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n throw new GalaSDKError('TOKEN_NAME_RESOLUTION_FAILED', { tokenName }, { cause });\n }\n // Only the documented object answer is accepted: a resolver that answers with a string could\n // hand back a five-part `key|instance` that a lenient parse would read as another collection.\n const record = typeof resolved === 'object' && resolved !== null ? resolved : undefined;\n const key = record === undefined ? undefined : tryParseTokenClassKey(record);\n const instance = byInstance ? (record as { instance?: unknown } | undefined)?.instance : '0';\n if (key === undefined || typeof instance !== 'string' || !INSTANCE.test(instance)) {\n throw new GalaSDKError('TOKEN_NAME_RESOLUTION_FAILED', { tokenName });\n }\n return instanceKey(key, instance);\n}\n"],"mappings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,EAAYD,EAAKQ,CAAQ,CAClC"}
1
+ {"version":3,"file":"token_ref.js","names":["BigNumber","DECIMAL","INSTANCE","writeQuantity","value","GalaSDKError","classKeyOf","splitClassKey","tryParseTokenClassKey","invalidReference","tokenClassKeyOf","field","key","instanceKey","checkQuantity","input","at","checkToken","tokenName","tokenClassKey","instance","chosen","resolveToken","token","resolver","resolved","byInstance","cause","isGalaError","record"],"sources":["../../../src/writes/token_ref.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport { splitClassKey, tryParseTokenClassKey } from '../utils/class_key.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { GalaChainTokenInstanceKey, TokenNameResolver, TokenQuantityInput } from './types.js';\n\n/** A plain decimal: digits, optionally a fraction. No sign, exponent, hex, spaces or separators. */\nconst DECIMAL = /^[0-9]+(?:\\.[0-9]+)?$/u;\nconst INSTANCE = /^[0-9]+$/u;\n\n/**\n * The quantity of a write, exactly as the caller wrote it: whole tokens as a plain decimal string\n * greater than zero. It is returned unchanged (never scaled to base units, never re-formatted), so\n * the signed amount is the amount the caller passed. A JS number is refused: it may already have\n * lost digits (`0.1 + 0.2`), and the chain receives strings.\n *\n * @throws GalaSDKError `INVALID_QUANTITY`.\n */\nexport function writeQuantity(value: unknown, field: string): string {\n if (typeof value === 'string' && DECIMAL.test(value) && new BigNumber(value).isGreaterThan(0)) {\n return value;\n }\n throw new GalaSDKError('INVALID_QUANTITY', { field, value: String(value) });\n}\n\n/**\n * The class key a write input names, or `undefined` when it is not one. Stricter than\n * `tryParseTokenClassKey` for the pipe form: `a|b|c|d|e` is refused rather than read as collection\n * `a|b`, because a five-part pipe string is someone's `class key|instance`, and signing a transfer\n * of a different collection is the one outcome a write must never have.\n */\nfunction classKeyOf(value: unknown): GalaChainTokenClassKey | undefined {\n if (typeof value !== 'string') return tryParseTokenClassKey(value);\n if (!value.includes('|')) return splitClassKey(value, '$');\n const parts = value.split('|');\n return parts.length === 4 ? splitClassKey(value, '|') : undefined;\n}\n\nfunction invalidReference(\n field: string,\n reason: 'missing' | 'ambiguous' | 'bad_class_key' | 'bad_instance',\n): GalaSDKError<'INVALID_TOKEN_REFERENCE'> {\n return new GalaSDKError('INVALID_TOKEN_REFERENCE', { field, reason });\n}\n\n/**\n * The class key `value` names, in the forms a write accepts (see {@link classKeyOf}), as the four\n * parts and nothing else; the gateway reads take their keys this way too.\n *\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`missing` for `undefined`, else `bad_class_key`).\n */\nexport function tokenClassKeyOf(value: unknown, field: string): GalaChainTokenClassKey {\n if (value === undefined) throw invalidReference(field, 'missing');\n const key = classKeyOf(value);\n if (key === undefined) throw invalidReference(field, 'bad_class_key');\n return {\n collection: key.collection,\n category: key.category,\n type: key.type,\n additionalKey: key.additionalKey,\n };\n}\n\n/** The fields of an instance key, and only those, in the order the chain DTOs carry them. */\nfunction instanceKey(key: GalaChainTokenClassKey, instance: string): GalaChainTokenInstanceKey {\n return {\n collection: key.collection,\n category: key.category,\n type: key.type,\n additionalKey: key.additionalKey,\n instance,\n };\n}\n\n/** A token named either way, checked synchronously; a name is resolved later (see {@link resolveToken}). */\nexport type CheckedToken =\n | { readonly kind: 'key'; readonly key: GalaChainTokenInstanceKey }\n | { readonly kind: 'name'; readonly tokenName: string };\n\n/** One checked token-and-quantity of a write. */\nexport interface CheckedQuantity {\n readonly quantity: string;\n readonly token: CheckedToken;\n}\n\n/**\n * Checks one token-and-quantity input: the quantity as `<at>quantity`, the token as `<at>token`\n * (`at` is `''` for a transfer, `tokens[2].` for a batch entry).\n *\n * @throws GalaSDKError `INVALID_QUANTITY`, `INVALID_TOKEN_REFERENCE`.\n */\nexport function checkQuantity(input: TokenQuantityInput, at: string): CheckedQuantity {\n return {\n quantity: writeQuantity(input.quantity, `${at}quantity`),\n token: checkToken(input, `${at}token`),\n };\n}\n\n/**\n * Checks how a write input names its token, without resolving a name (so invalid input never\n * costs a resolver round trip).\n *\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE`.\n */\nexport function checkToken(input: TokenQuantityInput, field: string): CheckedToken {\n const { tokenClassKey, tokenName, instance } = input;\n if (tokenName !== undefined) {\n if (tokenClassKey !== undefined || instance !== undefined) {\n throw invalidReference(field, 'ambiguous');\n }\n if (typeof tokenName !== 'string' || tokenName === '') throw invalidReference(field, 'missing');\n return { kind: 'name', tokenName };\n }\n const key = tokenClassKeyOf(tokenClassKey, field);\n const chosen: unknown = instance ?? '0';\n if (typeof chosen !== 'string' || !INSTANCE.test(chosen)) {\n throw invalidReference(field, 'bad_instance');\n }\n return { kind: 'key', key: instanceKey(key, chosen) };\n}\n\n/**\n * The instance key a checked token stands for. A name goes through the app's resolver at the\n * boundary of \"nothing was sent\": a rejection becomes `TOKEN_NAME_RESOLUTION_FAILED` (the\n * original as `cause`), an SDK error passes through, and an answer that is not a key is a failed\n * resolution too, so an unusable answer is never signed.\n *\n * @throws GalaSDKError `NO_TOKEN_NAME_RESOLVER`, `TOKEN_NAME_RESOLUTION_FAILED`.\n */\nexport async function resolveToken(\n token: CheckedToken,\n resolver: TokenNameResolver | undefined,\n): Promise<GalaChainTokenInstanceKey> {\n if (token.kind === 'key') return token.key;\n const { tokenName } = token;\n if (resolver === undefined) throw new GalaSDKError('NO_TOKEN_NAME_RESOLVER', { tokenName });\n let resolved: unknown;\n // Decided once, before the await: which answer shape is expected cannot change mid-call.\n let byInstance = false;\n try {\n if (resolver.resolveTokenInstance !== undefined) {\n byInstance = true;\n resolved = await resolver.resolveTokenInstance(tokenName);\n } else {\n resolved = await resolver.resolveTokenClassKey(tokenName);\n }\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n throw new GalaSDKError('TOKEN_NAME_RESOLUTION_FAILED', { tokenName }, { cause });\n }\n // Only the documented object answer is accepted: a resolver that answers with a string could\n // hand back a five-part `key|instance` that a lenient parse would read as another collection.\n const record = typeof resolved === 'object' && resolved !== null ? resolved : undefined;\n const key = record === undefined ? undefined : tryParseTokenClassKey(record);\n const instance = byInstance ? (record as { instance?: unknown } | undefined)?.instance : '0';\n if (key === undefined || typeof instance !== 'string' || !INSTANCE.test(instance)) {\n throw new GalaSDKError('TOKEN_NAME_RESOLUTION_FAILED', { tokenName });\n }\n return instanceKey(key, instance);\n}\n"],"mappings":"A,0LAOA,MAAMC,EAAU,yBACVC,EAAW,YAUjB,SAAgBC,EAAc,EAAgB,EAAuB,CACnE,GAAI,OAAOC,GAAU,UAAYH,EAAQ,KAAKG,CAAK,GAAK,IAAIJ,EAAUI,CAAK,CAAC,CAAC,cAAc,CAAC,EAC1F,OAAOA,EAET,MAAM,IAAIC,EAAa,mBAAoB,CAAE,QAAO,MAAO,OAAOD,CAAK,CAAE,CAAC,CAC5E,CAQA,SAASE,EAAW,EAAoD,CAItE,OAHI,OAAOF,GAAU,SAChBA,EAAM,SAAS,GAAG,EACTA,EAAM,MAAM,GACf,CAAC,CAAC,SAAW,EAAIG,EAAcH,EAAO,GAAG,EAAI,IAAA,GAFvBG,EAAcH,EAAO,GAAG,EADnBI,EAAsBJ,CAAK,CAInE,CAEA,SAASK,EACP,EACA,EACyC,CACzC,OAAO,IAAIJ,EAAa,0BAA2B,CAAE,QAAO,QAAO,CAAC,CACtE,CAQA,SAAgBK,EAAgB,EAAgB,EAAuC,CACrF,GAAIN,IAAU,IAAA,GAAW,MAAMK,EAAiBE,EAAO,SAAS,EAChE,IAAMC,EAAMN,EAAWF,CAAK,EAC5B,GAAIQ,IAAQ,IAAA,GAAW,MAAMH,EAAiBE,EAAO,eAAe,EACpE,MAAO,CACL,WAAYC,EAAI,WAChB,SAAUA,EAAI,SACd,KAAMA,EAAI,KACV,cAAeA,EAAI,aACrB,CACF,CAGA,SAASC,EAAY,EAA6B,EAA6C,CAC7F,MAAO,CACL,WAAYD,EAAI,WAChB,SAAUA,EAAI,SACd,KAAMA,EAAI,KACV,cAAeA,EAAI,cACnB,UACF,CACF,CAmBA,SAAgBE,E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IAAA,GAAYrB,EAAsBqB,CAAM,EACrET,EAAWM,EAAcG,GAA+C,SAAW,IACzF,GAAIjB,IAAQ,IAAA,IAAa,OAAOQ,GAAa,UAAY,CAAClB,EAAS,KAAKkB,CAAQ,EAC9E,MAAM,IAAIf,EAAa,+BAAgC,CAAE,WAAU,CAAC,EAEtE,OAAOQ,EAAYD,EAAKQ,CAAQ,CAClC,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"transfer.js","names":["GALA_TOKEN_CLASS_KEY","transferTokenDto","token","burnTokensDto","tokens"],"sources":["../../../src/writes/transfer.ts"],"sourcesContent":["import type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { GalaChainTokenInstanceKey } from './types.js';\n\n/** GALA's class key: what `transferGala` moves. */\nexport const GALA_TOKEN_CLASS_KEY: Readonly<GalaChainTokenClassKey> = Object.freeze({\n collection: 'GALA',\n category: 'Unit',\n type: 'none',\n additionalKey: 'none',\n});\n\n/** One token and the quantity of it a write moves, after checking and resolution. */\nexport interface ResolvedQuantity {\n readonly quantity: string;\n readonly key: GalaChainTokenInstanceKey;\n}\n\n/**\n * The unsigned `TransferToken` DTO: plain JSON, exactly the fields the chain signs, in the order\n * the gateway has always received them (`from, to, quantity, tokenInstance, uniqueKey`). No signer\n * field is ever added: the chain recovers the signer from the signature.\n */\nexport function transferTokenDto(\n from: string,\n to: string,\n token: ResolvedQuantity,\n uniqueKey: string,\n): Record<string, unknown> {\n return { from, to, quantity: token.quantity, tokenInstance: token.key, uniqueKey };\n}\n\n/** The unsigned `BurnTokens` DTO (`tokenInstances, uniqueKey`); burns are of the signer's own tokens. */\nexport function burnTokensDto(\n tokens: readonly ResolvedQuantity[],\n uniqueKey: string,\n): Record<string, unknown> {\n return {\n tokenInstances: tokens.map((token) => ({\n quantity: token.quantity,\n tokenInstanceKey: token.key,\n })),\n uniqueKey,\n };\n}\n"],"mappings":"AAIA,MAAaA,EAAyD,OAAO,OAAO,CAClF,WAAY,OACZ,SAAU,OACV,KAAM,OACN,cAAe,MACjB,CAAC,EAaD,SAAgBC,EACd,EACA,EACA,EACA,EACyB,CACzB,MAAO,CAAE,OAAM,KAAI,SAAUC,EAAM,SAAU,cAAeA,EAAM,IAAK,WAAU,CACnF,CAGA,SAAgBC,EACd,EACA,EACyB,CACzB,MAAO,CACL,eAAgBC,EAAO,IAAK,IAAW,CACrC,SAAUF,EAAM,SAChB,iBAAkBA,EAAM,GAC1B,EAAE,EACF,WACF,CACF"}
1
+ {"version":3,"file":"transfer.js","names":["GALA_TOKEN_CLASS_KEY","transferTokenDto","token","burnTokensDto","tokens"],"sources":["../../../src/writes/transfer.ts"],"sourcesContent":["import type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { GalaChainTokenInstanceKey } from './types.js';\n\n/** GALA's class key: what `transferGala` moves. */\nexport const GALA_TOKEN_CLASS_KEY: Readonly<GalaChainTokenClassKey> = Object.freeze({\n collection: 'GALA',\n category: 'Unit',\n type: 'none',\n additionalKey: 'none',\n});\n\n/** One token and the quantity of it a write moves, after checking and resolution. */\nexport interface ResolvedQuantity {\n readonly quantity: string;\n readonly key: GalaChainTokenInstanceKey;\n}\n\n/**\n * The unsigned `TransferToken` DTO: plain JSON, exactly the fields the chain signs, in the order\n * the gateway has always received them (`from, to, quantity, tokenInstance, uniqueKey`). No signer\n * field is ever added: the chain recovers the signer from the signature.\n */\nexport function transferTokenDto(\n from: string,\n to: string,\n token: ResolvedQuantity,\n uniqueKey: string,\n): Record<string, unknown> {\n return { from, to, quantity: token.quantity, tokenInstance: token.key, uniqueKey };\n}\n\n/** The unsigned `BurnTokens` DTO (`tokenInstances, uniqueKey`); burns are of the signer's own tokens. */\nexport function burnTokensDto(\n tokens: readonly ResolvedQuantity[],\n uniqueKey: string,\n): Record<string, unknown> {\n return {\n tokenInstances: tokens.map((token) => ({\n quantity: token.quantity,\n tokenInstanceKey: token.key,\n })),\n uniqueKey,\n };\n}\n"],"mappings":"AAIA,MAAaA,EAAyD,OAAO,OAAO,CAClF,WAAY,OACZ,SAAU,OACV,KAAM,OACN,cAAe,MACjB,CAAC,EAaD,SAAgBC,EACd,EACA,EACA,EACA,EACyB,CACzB,MAAO,CAAE,OAAM,KAAI,SAAUC,EAAM,SAAU,cAAeA,EAAM,IAAK,WAAU,CACnF,CAGA,SAAgBC,EACd,EACA,EACyB,CACzB,MAAO,CACL,eAAgBC,EAAO,IAAK,IAAW,CACrC,SAAUF,EAAM,SAChB,iBAAkBA,EAAM,GAC1B,EAAE,EACF,WACF,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":["GATEWAY_WRITE_METHODS","GATEWAY_WRITE_BATCH_LIMITS"],"sources":["../../../src/writes/types.ts"],"sourcesContent":["import type { GalaChainSigner } from '../classes/signers.js';\nimport type { HttpRequestor } from '../types/http_requestor.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { WireOptions } from '../types/wire.js';\n\n/** The token-contract methods `GatewayWrites` signs and submits, as a closed set. */\nexport const GATEWAY_WRITE_METHODS = [\n 'TransferToken',\n 'BurnTokens',\n 'LockToken',\n 'UnlockToken',\n] as const;\n\n/** One member of {@link GATEWAY_WRITE_METHODS}. */\nexport type GatewayWriteMethod = (typeof GATEWAY_WRITE_METHODS)[number];\n\n/** The most tokens one write may carry (GalaChain batch limits; a burn is irreversible, so fewer). */\nexport const GATEWAY_WRITE_BATCH_LIMITS: Readonly<\n Record<Exclude<GatewayWriteMethod, 'TransferToken'>, number>\n> = Object.freeze({ BurnTokens: 50, LockToken: 100, UnlockToken: 100 });\n\n/** A token class key plus the instance of it a write moves (`\"0\"` for a fungible token). */\nexport interface GalaChainTokenInstanceKey extends GalaChainTokenClassKey {\n instance: string;\n}\n\n/**\n * A token class key as a write accepts it: `collection|category|type|additionalKey` (exactly four\n * parts), the `$`-joined composite key (split from the right, so a `$GMUSIC` collection stays\n * whole), or the four-part object. A bare symbol is never one, and none is derived from it.\n */\nexport type TokenClassKeyInput = string | GalaChainTokenClassKey;\n\n/**\n * Turns a product's token NAME (a launchpad token's name, say) into the chain key a write signs.\n * Optional: it is consulted only for inputs that name a token by `tokenName`; a `tokenClassKey`\n * never needs it. A rejection is `TOKEN_NAME_RESOLUTION_FAILED` (pre-send, the original error as\n * `cause`); an SDK error it throws passes through as it is.\n */\nexport interface TokenNameResolver {\n /** The class key `tokenName` stands for; the write moves its fungible instance `\"0\"`. */\n resolveTokenClassKey(tokenName: string): Promise<GalaChainTokenClassKey>;\n /**\n * The instance key `tokenName` stands for, when the product names a specific instance. When\n * present it is used instead of {@link resolveTokenClassKey}.\n */\n resolveTokenInstance?(tokenName: string): Promise<GalaChainTokenInstanceKey>;\n}\n\n/**\n * One token and amount of a write. Name the token with exactly one of `tokenClassKey` (plus an\n * optional `instance`) or `tokenName` (needs a `TokenNameResolver`).\n */\nexport interface TokenQuantityInput {\n /** The token's class key. */\n tokenClassKey?: TokenClassKeyInput | undefined;\n /** The instance of `tokenClassKey` to move, a decimal string; default `\"0\"` (fungible). */\n instance?: string | undefined;\n /** A product token name, resolved by the configured `TokenNameResolver`. */\n tokenName?: string | undefined;\n /**\n * The amount in WHOLE tokens, as the decimal string the chain is to receive (`\"1.5\"` is one and a\n * half tokens). It is signed exactly as written: never scaled to base units, never re-formatted\n * (`\"1.50\"` stays `\"1.50\"`).\n */\n quantity: string;\n}\n\n/** Options every write takes. */\nexport interface WriteKeyInput {\n /**\n * The write's idempotency key: 1 to 128 characters of `A-Za-z0-9._:-`. Reuse a key only to retry\n * the SAME write. Omitted: a fresh `<uniqueKeyPrefix><uuid v4>` is minted (CSPRNG).\n */\n uniqueKey?: string | undefined;\n}\n\n/** `transferGala`: GALA (`GALA|Unit|none|none`, instance `\"0\"`) to a recipient. */\nexport interface TransferGalaInput extends WriteKeyInput {\n /**\n * The recipient: an Ethereum account (`eth|<40 hex>`, `0x<40 hex>` or `<40 hex>`, any casing\n * but a wrong EIP-55 checksum; always sent as `eth|<checksummed>`), or a `client|` alias (sent\n * as written). `eth|0x<40 hex>` is not an address form and is refused\n * (`INVALID_ETH_USER_REF_PREFIX`).\n */\n to: string;\n /** Whole GALA, as a decimal string (see {@link TokenQuantityInput.quantity}). */\n quantity: string;\n}\n\n/** `transferToken`: one token to a recipient. */\nexport interface TransferTokenInput extends TokenQuantityInput, WriteKeyInput {\n /** The recipient (see {@link TransferGalaInput.to}). */\n to: string;\n}\n\n/** `burnTokens`: 1 to 50 tokens, burned from the writer's own balance. IRREVERSIBLE. */\nexport interface BurnTokensInput extends WriteKeyInput {\n tokens: readonly TokenQuantityInput[];\n}\n\n/** `lockTokens`: 1 to 100 tokens of the writer's, held under one lock. */\nexport interface LockTokensInput extends WriteKeyInput {\n tokens: readonly TokenQuantityInput[];\n /** Who may unlock (see {@link TransferGalaInput.to} for the forms); default the writer itself. */\n lockAuthority?: string | undefined;\n /** When the hold expires, in epoch milliseconds; `0` (or omitted) means it never expires. */\n expires?: number | undefined;\n /** A name for the hold, so it can be unlocked by name. */\n name?: string | undefined;\n}\n\n/** `unlockTokens`: 1 to 100 tokens of the writer's, released from their hold. */\nexport interface UnlockTokensInput extends WriteKeyInput {\n tokens: readonly TokenQuantityInput[];\n /** The name of the hold to release. */\n name?: string | undefined;\n}\n\n/** How to reach and sign for the gateway. */\nexport interface GatewayWritesOptions {\n /**\n * The GalaChain gateway base URL; every write POSTs to\n * `<gatewayBaseUrl>/api/asset/token-contract/<Method>`. `''` sends the bare path, for an\n * `httpRequestor` that resolves paths against its own base (an HTTP client with a base URL).\n */\n gatewayBaseUrl: string;\n /** Signs every write. The DTO it is handed is exactly what is signed; nothing is added to it. */\n signer: GalaChainSigner;\n /**\n * The identity the writes are made AS: the sender of a transfer, the owner of what is burned,\n * locked or unlocked, and the default lock authority, in the forms of\n * {@link TransferGalaInput.to} (an Ethereum account is always sent as `eth|<checksummed>`).\n * It must be the account the signer's key acts as; the chain refuses a write whose sender is\n * not its signer.\n */\n walletAddress: string;\n /** The HTTP requestor; default the global `fetch`. Its own rejections reach the caller unchanged. */\n httpRequestor?: HttpRequestor | undefined;\n /** Timeout of every write request in milliseconds (default 30 000); `Infinity` arms no timer. */\n requestTimeoutMs?: number | undefined;\n /** Headers of every write request (`userAgent`, `headers`); see {@link WireOptions}. */\n wire?: WireOptions | undefined;\n /** Resolves `tokenName` inputs; only needed when a write names a token that way. */\n tokenNameResolver?: TokenNameResolver | undefined;\n /** Prefix of every minted `uniqueKey` (default `galaswap-operation-`); see `UniqueKeyOptions`. */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/**\n * What a gateway write returns once GalaChain accepted it (`Status: 1`).\n */\nexport interface GatewayWriteReceipt {\n /** The method that was submitted. */\n readonly method: GatewayWriteMethod;\n /** The `uniqueKey` that was signed (the minted one when the caller gave none). */\n readonly uniqueKey: string;\n /**\n * The chain transaction id: the gateway's `x-transaction-id` header, else a top-level\n * `transactionId` of the answer; `undefined` when it named none. Never guessed from the `Data`\n * items (a balance's `id` is not a transaction id).\n */\n readonly transactionId: string | undefined;\n /** The block the write landed in, from the gateway's `x-block-number` header, when it sent one. */\n readonly blockNumber: number | undefined;\n /** The chain's result: the answer's `Data` (balances, holds or burns), as GalaChain returned it. */\n readonly data: unknown;\n /** The whole parsed answer. */\n readonly body: unknown;\n}\n"],"mappings":"AAMA,MAAaA,EAAwB,CACnC,gBACA,aACA,YACA,aACF,EAMaC,EAET,OAAO,OAAO,CAAE,WAAY,GAAI,UAAW,IAAK,YAAa,GAAI,CAAC"}
1
+ {"version":3,"file":"types.js","names":["GATEWAY_WRITE_METHODS","GATEWAY_WRITE_BATCH_LIMITS"],"sources":["../../../src/writes/types.ts"],"sourcesContent":["import type { GalaChainSigner } from '../classes/signers.js';\nimport type { HttpRequestor } from '../types/http_requestor.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { WireOptions } from '../types/wire.js';\n\n/** The token-contract methods `GatewayWrites` signs and submits, as a closed set. */\nexport const GATEWAY_WRITE_METHODS = [\n 'TransferToken',\n 'BurnTokens',\n 'LockToken',\n 'UnlockToken',\n] as const;\n\n/** One member of {@link GATEWAY_WRITE_METHODS}. */\nexport type GatewayWriteMethod = (typeof GATEWAY_WRITE_METHODS)[number];\n\n/** The most tokens one write may carry (GalaChain batch limits; a burn is irreversible, so fewer). */\nexport const GATEWAY_WRITE_BATCH_LIMITS: Readonly<\n Record<Exclude<GatewayWriteMethod, 'TransferToken'>, number>\n> = Object.freeze({ BurnTokens: 50, LockToken: 100, UnlockToken: 100 });\n\n/** A token class key plus the instance of it a write moves (`\"0\"` for a fungible token). */\nexport interface GalaChainTokenInstanceKey extends GalaChainTokenClassKey {\n instance: string;\n}\n\n/**\n * A token class key as a write accepts it: `collection|category|type|additionalKey` (exactly four\n * parts), the `$`-joined composite key (split from the right, so a `$GMUSIC` collection stays\n * whole), or the four-part object. A bare symbol is never one, and none is derived from it.\n */\nexport type TokenClassKeyInput = string | GalaChainTokenClassKey;\n\n/**\n * Turns a product's token NAME (a launchpad token's name, say) into the chain key a write signs.\n * Optional: it is consulted only for inputs that name a token by `tokenName`; a `tokenClassKey`\n * never needs it. A rejection is `TOKEN_NAME_RESOLUTION_FAILED` (pre-send, the original error as\n * `cause`); an SDK error it throws passes through as it is.\n */\nexport interface TokenNameResolver {\n /** The class key `tokenName` stands for; the write moves its fungible instance `\"0\"`. */\n resolveTokenClassKey(tokenName: string): Promise<GalaChainTokenClassKey>;\n /**\n * The instance key `tokenName` stands for, when the product names a specific instance. When\n * present it is used instead of {@link resolveTokenClassKey}.\n */\n resolveTokenInstance?(tokenName: string): Promise<GalaChainTokenInstanceKey>;\n}\n\n/**\n * One token and amount of a write. Name the token with exactly one of `tokenClassKey` (plus an\n * optional `instance`) or `tokenName` (needs a `TokenNameResolver`).\n */\nexport interface TokenQuantityInput {\n /** The token's class key. */\n tokenClassKey?: TokenClassKeyInput | undefined;\n /** The instance of `tokenClassKey` to move, a decimal string; default `\"0\"` (fungible). */\n instance?: string | undefined;\n /** A product token name, resolved by the configured `TokenNameResolver`. */\n tokenName?: string | undefined;\n /**\n * The amount in WHOLE tokens, as the decimal string the chain is to receive (`\"1.5\"` is one and a\n * half tokens). It is signed exactly as written: never scaled to base units, never re-formatted\n * (`\"1.50\"` stays `\"1.50\"`).\n */\n quantity: string;\n}\n\n/** Options every write takes. */\nexport interface WriteKeyInput {\n /**\n * The write's idempotency key: 1 to 128 characters of `A-Za-z0-9._:-`. Reuse a key only to retry\n * the SAME write. Omitted: a fresh `<uniqueKeyPrefix><uuid v4>` is minted (CSPRNG).\n */\n uniqueKey?: string | undefined;\n}\n\n/** `transferGala`: GALA (`GALA|Unit|none|none`, instance `\"0\"`) to a recipient. */\nexport interface TransferGalaInput extends WriteKeyInput {\n /**\n * The recipient: an Ethereum account (`eth|<40 hex>`, `0x<40 hex>` or `<40 hex>`, any casing\n * but a wrong EIP-55 checksum; always sent as `eth|<checksummed>`), or a `client|` alias (sent\n * as written). `eth|0x<40 hex>` is not an address form and is refused\n * (`INVALID_ETH_USER_REF_PREFIX`).\n */\n to: string;\n /** Whole GALA, as a decimal string (see {@link TokenQuantityInput.quantity}). */\n quantity: string;\n}\n\n/** `transferToken`: one token to a recipient. */\nexport interface TransferTokenInput extends TokenQuantityInput, WriteKeyInput {\n /** The recipient (see {@link TransferGalaInput.to}). */\n to: string;\n}\n\n/** `burnTokens`: 1 to 50 tokens, burned from the writer's own balance. IRREVERSIBLE. */\nexport interface BurnTokensInput extends WriteKeyInput {\n tokens: readonly TokenQuantityInput[];\n}\n\n/** `lockTokens`: 1 to 100 tokens of the writer's, held under one lock. */\nexport interface LockTokensInput extends WriteKeyInput {\n tokens: readonly TokenQuantityInput[];\n /** Who may unlock (see {@link TransferGalaInput.to} for the forms); default the writer itself. */\n lockAuthority?: string | undefined;\n /** When the hold expires, in epoch milliseconds; `0` (or omitted) means it never expires. */\n expires?: number | undefined;\n /** A name for the hold, so it can be unlocked by name. */\n name?: string | undefined;\n}\n\n/** `unlockTokens`: 1 to 100 tokens of the writer's, released from their hold. */\nexport interface UnlockTokensInput extends WriteKeyInput {\n tokens: readonly TokenQuantityInput[];\n /** The name of the hold to release. */\n name?: string | undefined;\n}\n\n/** How to reach and sign for the gateway. */\nexport interface GatewayWritesOptions {\n /**\n * The GalaChain gateway base URL; every write POSTs to\n * `<gatewayBaseUrl>/api/asset/token-contract/<Method>`. `''` sends the bare path, for an\n * `httpRequestor` that resolves paths against its own base (an HTTP client with a base URL).\n */\n gatewayBaseUrl: string;\n /** Signs every write. The DTO it is handed is exactly what is signed; nothing is added to it. */\n signer: GalaChainSigner;\n /**\n * The identity the writes are made AS: the sender of a transfer, the owner of what is burned,\n * locked or unlocked, and the default lock authority, in the forms of\n * {@link TransferGalaInput.to} (an Ethereum account is always sent as `eth|<checksummed>`).\n * It must be the account the signer's key acts as; the chain refuses a write whose sender is\n * not its signer.\n */\n walletAddress: string;\n /** The HTTP requestor; default the global `fetch`. Its own rejections reach the caller unchanged. */\n httpRequestor?: HttpRequestor | undefined;\n /** Timeout of every write request in milliseconds (default 30 000); `Infinity` arms no timer. */\n requestTimeoutMs?: number | undefined;\n /** Headers of every write request (`userAgent`, `headers`); see {@link WireOptions}. */\n wire?: WireOptions | undefined;\n /** Resolves `tokenName` inputs; only needed when a write names a token that way. */\n tokenNameResolver?: TokenNameResolver | undefined;\n /** Prefix of every minted `uniqueKey` (default `galaswap-operation-`); see `UniqueKeyOptions`. */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/**\n * What a gateway write returns once GalaChain accepted it (`Status: 1`).\n */\nexport interface GatewayWriteReceipt {\n /** The method that was submitted. */\n readonly method: GatewayWriteMethod;\n /** The `uniqueKey` that was signed (the minted one when the caller gave none). */\n readonly uniqueKey: string;\n /**\n * The chain transaction id: the gateway's `x-transaction-id` header, else a top-level\n * `transactionId` of the answer; `undefined` when it named none. Never guessed from the `Data`\n * items (a balance's `id` is not a transaction id).\n */\n readonly transactionId: string | undefined;\n /** The block the write landed in, from the gateway's `x-block-number` header, when it sent one. */\n readonly blockNumber: number | undefined;\n /** The chain's result: the answer's `Data` (balances, holds or burns), as GalaChain returned it. */\n readonly data: unknown;\n /** The whole parsed answer. */\n readonly body: unknown;\n}\n"],"mappings":"AAMA,MAAaA,EAAwB,CACnC,gBACA,aACA,YACA,aACF,EAMaC,EAET,OAAO,OAAO,CAAE,WAAY,GAAI,UAAW,IAAK,YAAa,GAAI,CAAC,E"}