@gala-chain/gala-core-sdk 1.1.0-beta.2 → 1.1.0-beta.4

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["isRecord","textEncoder","textEncoder","globalObject","isRecord","isRecord","isRecord","isRecord","stringField","DEFAULT_REQUEST_TIMEOUT_MS"],"sources":["../src/classes/error_catalog.ts","../src/classes/error_phase_table.ts","../src/classes/error_phases.ts","../src/utils/error_brand.ts","../src/classes/gala_sdk_error.ts","../src/utils/eth_address.ts","../src/writes/identity.ts","../src/utils/eip712.ts","../src/utils/signing.ts","../src/classes/signers.ts","../src/utils/chain_dto_signing.ts","../src/utils/typed_data.ts","../src/utils/dto_operation.ts","../src/utils/wallet_rejection.ts","../src/utils/pre_send.ts","../src/version.ts","../src/utils/transport.ts","../src/utils/axios_requestor.ts","../src/utils/ethers_provider.ts","../src/utils/fetch_failure.ts","../src/utils/failure_outcomes.ts","../src/utils/failure_view.ts","../src/utils/class_key.ts","../src/utils/unique_key_syntax.ts","../src/utils/unique_key.ts","../src/utils/wallet_keys.ts","../src/writes/lock.ts","../src/writes/submit.ts","../src/writes/token_ref.ts","../src/writes/transfer.ts","../src/writes/types.ts","../src/writes/gateway_writes.ts","../src/reads/parse.ts","../src/reads/request.ts","../src/reads/types.ts","../src/reads/gateway_reads.ts","../src/config/environments.ts"],"sourcesContent":["/**\n * The catalog of every error `@gala-chain/gala-core-sdk` throws: the SINGLE source of truth for\n * its `code`, the named parameters it carries and the English template its `message` is generated\n * from. A product SDK (gswap-sdk, launchpad-sdk) keeps its OWN catalog of the codes only it throws,\n * and its error class (a subclass of `GalaSDKError`) reads both; no code is defined twice.\n *\n * - `code` is the only discriminator. It is stable: apps branch on it, never on message text.\n * - `params` are the named placeholders of the error: a flat object of primitives (string,\n * number, boolean) that an app feeds to its own localization (i18next, ICU, FormatJS).\n * Raw server payloads are never params (they are `error.body` / `error.bodyText`), and no\n * secret (private key, signature, raw DTO) ever is.\n * - `template` is English with `{placeholder}` markers. `error.message` is generated from it\n * and the params, so the two cannot drift. It is for logs and developers: it is not stable and\n * must not be shown to users or matched on.\n *\n * Every placeholder in a template is a declared param and every declared param is a placeholder,\n * except the few `unrendered` params that carry server text for the app and are kept out of\n * `message` on purpose (pinned by tests/error_catalog.test.ts). Facts that are not placeholders\n * (HTTP status, URL, `uniqueKey`, transaction ids, the raw body, the cause) are typed properties of\n * the error, see {@link GalaErrorContext}.\n */\n\nimport type { GalaErrorPhase } from './error_phases.js';\n\n/**\n * The kinds a param can have: a primitive, or a CLOSED set of string tokens (a readonly tuple).\n * A closed set is a documented union: an app maps each member to its own text and can check that\n * it covered all of them, and a new member is a compile error until it does.\n */\nexport type GalaErrorParamKind = 'string' | 'number' | 'boolean' | readonly string[];\n\n/** One catalog entry (of this catalog, or of a product SDK's own catalog). */\nexport interface GalaErrorCatalogEntry {\n /** The phase this code is thrown in, unless a throw site says otherwise (see {@link GalaErrorPhase}). */\n readonly phase: GalaErrorPhase;\n /** English message template with `{placeholder}` markers. */\n readonly template: string;\n /** Param name to kind. Every param is required and appears in the template, except `unrendered`. */\n readonly params: Readonly<Record<string, GalaErrorParamKind>>;\n /**\n * Params that are carried for the app but deliberately NOT placeholders of the template. Used\n * for `serverMessage` on the codes whose failing answer may be anything (a proxy's page, a\n * validation list): the server's text is data for the app to relay or ignore, and keeping it out\n * of `message` means it cannot reach a log line or a user interface by accident.\n */\n readonly unrendered?: readonly string[];\n}\n\n/**\n * Why a private key was refused (`INVALID_PRIVATE_KEY.params.reason`). A token for the app to map\n * to its own text, never English and never any part of the key.\n *\n * - `wrong_length`: raw bytes that are not 32 bytes long (a `./bridge` Solana secret key: not 64\n * bytes once decoded).\n * - `bad_encoding`: a string that is neither 64 hex characters (optionally `0x`-prefixed, 63 is\n * left-padded) nor a 44-character base64 string (`./bridge`: an Ethereum key that is not `0x`\n * and 64 hex characters; a Solana secret key that is not base58, or whose public half does not\n * match its secret half).\n * - `not_on_curve`: 32 bytes that are not a valid secp256k1 secret scalar.\n * - `no_key_provided`: a lazy key provider returned something that is not a string.\n */\nexport const INVALID_PRIVATE_KEY_REASONS = [\n 'wrong_length',\n 'bad_encoding',\n 'not_on_curve',\n 'no_key_provided',\n] as const;\n\n/** One member of {@link INVALID_PRIVATE_KEY_REASONS}. */\nexport type InvalidPrivateKeyReason = (typeof INVALID_PRIVATE_KEY_REASONS)[number];\n\n/**\n * Why a signer could not produce a signature (`SIGNING_FAILED.params.reason`). A token for the\n * app to map to its own text.\n *\n * - `user_rejected`: the person declined in their wallet (an EIP-1193 `4001`, an ethers\n * `ACTION_REJECTED`, or a wallet that words it \"User rejected/denied ...\"). Nothing is wrong:\n * they may simply try again.\n * - `failed`: anything else the signer threw (a locked wallet, an unreachable extension, a wallet\n * that refused). The original error is `cause`.\n */\nexport const SIGNING_FAILURE_REASONS = ['user_rejected', 'failed'] as const;\n\n/** One member of {@link SIGNING_FAILURE_REASONS}. */\nexport type SigningFailureReason = (typeof SIGNING_FAILURE_REASONS)[number];\n\n/**\n * Why a gateway write refused the token it was asked to move\n * (`INVALID_TOKEN_REFERENCE.params.reason`). A token for the app to map to its own text.\n *\n * - `missing`: neither `tokenClassKey` nor `tokenName` was given.\n * - `ambiguous`: more than one way of naming the token was given (`tokenClassKey` and\n * `tokenName`, or a `tokenName` with an `instance`: a resolved name decides its own instance).\n * - `bad_class_key`: `tokenClassKey` is not a class key: a pipe string needs exactly four\n * non-empty parts, a `$` string at least four (split from the right), an object four non-empty\n * strings. A bare symbol is never a class key and none is derived from it.\n * - `bad_instance`: `instance` is not a string of decimal digits.\n */\nexport const INVALID_TOKEN_REFERENCE_REASONS = [\n 'missing',\n 'ambiguous',\n 'bad_class_key',\n 'bad_instance',\n] as const;\n\n/** One member of {@link INVALID_TOKEN_REFERENCE_REASONS}. */\nexport type InvalidTokenReferenceReason = (typeof INVALID_TOKEN_REFERENCE_REASONS)[number];\n\n/**\n * The `GatewayWrites` options that are refused when missing or of the wrong type\n * (`INVALID_WRITES_OPTION.params.option`). `walletAddress`, `requestTimeoutMs` and\n * `uniqueKeyPrefix` have codes of their own (`INVALID_WALLET_ADDRESS`, `INVALID_TIMEOUT`,\n * `INVALID_UNIQUE_KEY_PREFIX`).\n */\nexport const GATEWAY_WRITES_OPTIONS = [\n 'signer',\n 'gatewayBaseUrl',\n 'httpRequestor',\n 'tokenNameResolver',\n] as const;\n\n/** One member of {@link GATEWAY_WRITES_OPTIONS}. */\nexport type GatewayWritesOption = (typeof GATEWAY_WRITES_OPTIONS)[number];\n\n/**\n * Why the outcome of a gateway write is unknown (`GATEWAY_WRITE_OUTCOME_UNKNOWN.params.reason`).\n * Both say the same thing about the write (it MAY have been applied: never send it again under a\n * fresh key, check `error.uniqueKey` instead) and differ only in what happened to the request.\n *\n * - `timeout`: the POST exceeded `requestTimeoutMs`; the request may still be running.\n * - `transport`: the POST failed before an answer was read (offline, connection reset, DNS, CORS,\n * a body that broke off). The bytes may have reached the gateway.\n */\nexport const GATEWAY_WRITE_OUTCOME_UNKNOWN_REASONS = ['timeout', 'transport'] as const;\n\n/** One member of {@link GATEWAY_WRITE_OUTCOME_UNKNOWN_REASONS}. */\nexport type GatewayWriteOutcomeUnknownReason =\n (typeof GATEWAY_WRITE_OUTCOME_UNKNOWN_REASONS)[number];\n\n/**\n * The `GatewayReads` options that are refused when missing or of the wrong type\n * (`INVALID_READS_OPTION.params.option`). `requestTimeoutMs` has its own code (`INVALID_TIMEOUT`).\n */\nexport const GATEWAY_READS_OPTIONS = ['gatewayBaseUrl', 'httpRequestor'] as const;\n\n/** One member of {@link GATEWAY_READS_OPTIONS}. */\nexport type GatewayReadsOption = (typeof GATEWAY_READS_OPTIONS)[number];\n\n/**\n * The part of a paginated read that was refused (`INVALID_PAGE_REQUEST.params.field`):\n *\n * - `limit` / `pageSize`: results per page, a whole number from 1 to 10 000;\n * - `maxPages`: how many pages a `fetchAll...` read may walk, a whole number from 1 to 10 000;\n * - `bookmark`: the previous page's `nextPageBookmark`, a string.\n */\nexport const PAGE_REQUEST_FIELDS = ['limit', 'pageSize', 'maxPages', 'bookmark'] as const;\n\n/** One member of {@link PAGE_REQUEST_FIELDS}. */\nexport type PageRequestField = (typeof PAGE_REQUEST_FIELDS)[number];\n\n/**\n * Why a wallet provider is not connected (`WALLET_NOT_CONNECTED.params.reason`):\n *\n * - `not_connected`: `connect()` was never called, or `disconnect()` was;\n * - `disconnected`: the wallet reported it is disconnected (EIP-1193 `4900` / `4901`, a\n * `disconnect` event, or an `accountsChanged` with no account);\n * - `unauthorized`: the wallet refused the account (EIP-1193 `4100`): the person has not granted\n * this app access to it.\n */\nexport const WALLET_NOT_CONNECTED_REASONS = [\n 'not_connected',\n 'disconnected',\n 'unauthorized',\n] as const;\n\n/** One member of {@link WALLET_NOT_CONNECTED_REASONS}. */\nexport type WalletNotConnectedReason = (typeof WALLET_NOT_CONNECTED_REASONS)[number];\n\n/**\n * Why connecting a wallet provider failed (`WALLET_CONNECTION_FAILED.params.reason`):\n *\n * - `no_accounts`: the wallet answered `eth_requestAccounts` with no account;\n * - `user_rejected`: the person declined the connection in their wallet (EIP-1193 `4001`);\n * - `failed`: anything else the wallet threw (the original error is `cause`).\n */\nexport const WALLET_CONNECTION_FAILURE_REASONS = [\n 'no_accounts',\n 'user_rejected',\n 'failed',\n] as const;\n\n/** One member of {@link WALLET_CONNECTION_FAILURE_REASONS}. */\nexport type WalletConnectionFailureReason = (typeof WALLET_CONNECTION_FAILURE_REASONS)[number];\n\n/**\n * What a wallet provider was built without (`INVALID_WALLET_PROVIDER_CONFIG.params.missing`):\n *\n * - `eip1193_provider`: an `ExternalWalletProvider` / `GalaWalletProvider` needs the wallet's\n * provider object (`window.ethereum`, an EIP-6963 announcement, `window.gala`);\n * - `private_key_or_eip1193_provider`: `createWalletProvider` needs one of the two.\n */\nexport const WALLET_PROVIDER_CONFIG_MISSING = [\n 'eip1193_provider',\n 'private_key_or_eip1193_provider',\n] as const;\n\n/** One member of {@link WALLET_PROVIDER_CONFIG_MISSING}. */\nexport type WalletProviderConfigMissing = (typeof WALLET_PROVIDER_CONFIG_MISSING)[number];\n\n/**\n * Why `createWallet` refused its input (`INVALID_WALLET_INPUT.params.reason`), never naming any part\n * of it (it may be a key or a mnemonic):\n *\n * - `empty`: nothing but whitespace;\n * - `unrecognized_format`: neither 64 hex digits nor 12 / 24 words of letters;\n * - `unknown_mnemonic_word`: a word that is not in the BIP-39 English wordlist;\n * - `mnemonic_checksum`: every word is known but the phrase's checksum is wrong (a typo or a\n * swapped word).\n */\nexport const WALLET_INPUT_PROBLEMS = [\n 'empty',\n 'unrecognized_format',\n 'unknown_mnemonic_word',\n 'mnemonic_checksum',\n] as const;\n\n/** One member of {@link WALLET_INPUT_PROBLEMS}. */\nexport type WalletInputProblem = (typeof WALLET_INPUT_PROBLEMS)[number];\n\n/** The external networks `./bridge` bridges to and from. */\nexport const BRIDGE_NETWORKS = ['Ethereum', 'Solana'] as const;\n\n/** One member of {@link BRIDGE_NETWORKS}. */\nexport type BridgeNetwork = (typeof BRIDGE_NETWORKS)[number];\n\n/**\n * Why a bridge amount was refused (`INVALID_BRIDGE_AMOUNT.params.reason`):\n *\n * - `not_a_number`: not a finite decimal number;\n * - `not_positive`: zero or negative (a bridge of nothing only wastes the fee);\n * - `too_many_decimals`: more decimal places than the token has (it would be rounded).\n */\nexport const BRIDGE_AMOUNT_PROBLEMS = [\n 'not_a_number',\n 'not_positive',\n 'too_many_decimals',\n] as const;\n\n/** One member of {@link BRIDGE_AMOUNT_PROBLEMS}. */\nexport type BridgeAmountProblem = (typeof BRIDGE_AMOUNT_PROBLEMS)[number];\n\n/**\n * Where a bridge-out failed AFTER GalaConnect accepted its `RequestTokenBridgeOut`\n * (`BRIDGE_OUT_OUTCOME_UNKNOWN.params.step`):\n *\n * - `request_id`: the answer had no bridge request id;\n * - `bridge_token_out`: the `BridgeTokenOut` call failed;\n * - `transaction_hash`: the `BridgeTokenOut` answer had no transaction hash.\n */\nexport const BRIDGE_OUT_STEPS = ['request_id', 'bridge_token_out', 'transaction_hash'] as const;\n\n/** One member of {@link BRIDGE_OUT_STEPS}. */\nexport type BridgeOutStep = (typeof BRIDGE_OUT_STEPS)[number];\n\n/**\n * Where a bridge-in deposit failed once it was being sent (`BRIDGE_DEPOSIT_OUTCOME_UNKNOWN.params.step`):\n *\n * - `send`: sending the deposit transaction failed (it may have reached the network);\n * - `confirmation`: the deposit was sent and its confirmation failed or is unknown;\n * - `registration`: the deposit is confirmed and registering it with GalaConnect failed.\n */\nexport const BRIDGE_DEPOSIT_STEPS = ['send', 'confirmation', 'registration'] as const;\n\n/** One member of {@link BRIDGE_DEPOSIT_STEPS}. */\nexport type BridgeDepositStep = (typeof BRIDGE_DEPOSIT_STEPS)[number];\n\n/**\n * Why a token cannot be wrapped or unwrapped (`TOKEN_NOT_WRAPPABLE.params.reason`):\n *\n * - `not_listed`: the wrappable token list does not have it;\n * - `no_counterpart`: the token it wraps to / unwraps from is not listed;\n * - `unknown_channel`: its channel (or its counterpart's) is not one a wrap moves between.\n */\nexport const WRAP_REFUSAL_REASONS = ['not_listed', 'no_counterpart', 'unknown_channel'] as const;\n\n/** One member of {@link WRAP_REFUSAL_REASONS}. */\nexport type WrapRefusalReason = (typeof WRAP_REFUSAL_REASONS)[number];\n\n/** The two cross-channel directions (`INVALID_WRAP_DIRECTION.params.direction`). */\nexport const WRAP_DIRECTIONS = ['wrap', 'unwrap'] as const;\n\n/** One member of {@link WRAP_DIRECTIONS}. */\nexport type WrapDirection = (typeof WRAP_DIRECTIONS)[number];\n\n/** The whole core catalog. Add a code here before throwing it anywhere in this package. */\nexport const GALA_ERROR_CATALOG = {\n // ---------------------------------------------------------------------------------- transport\n REQUEST_TIMEOUT: {\n phase: 'in_flight',\n template: 'Request to {url} timed out after {timeoutMs} ms.',\n params: { url: 'string', timeoutMs: 'number' },\n },\n TRANSPORT_ERROR: {\n phase: 'in_flight',\n template: 'The request to {url} failed before the server answered.',\n params: { url: 'string' },\n },\n INVALID_TIMEOUT: {\n phase: 'pre_send',\n template:\n '{field} must be a positive number of milliseconds, or Infinity for no timeout (got {value}).',\n params: { field: 'string', value: 'number' },\n },\n\n // ------------------------------------------------------------------------------ wallet / keys\n GALA_WALLET_NOT_AVAILABLE: {\n phase: 'pre_send',\n template: 'Gala wallet is not available. Please ensure the Gala wallet is connected.',\n params: {},\n },\n WALLET_UNAVAILABLE: {\n phase: 'pre_send',\n template: 'No wallet is connected.',\n params: {},\n },\n MALFORMED_WALLET_REQUEST: {\n phase: 'pre_send',\n template: 'Wallet {method} request is malformed.',\n params: { method: 'string' },\n },\n UNSUPPORTED_WALLET_METHOD: {\n phase: 'pre_send',\n template: 'Unsupported wallet method {method}.',\n params: { method: 'string' },\n },\n INVALID_SIGNATURE: {\n phase: 'pre_send',\n template: 'Wallet returned an invalid {scheme} signature.',\n params: { scheme: 'string' },\n },\n INVALID_CHAIN_ID: {\n phase: 'pre_send',\n template: 'Wallet returned an invalid chain id ({chainId}).',\n params: { chainId: 'string' },\n },\n SIGNER_ADDRESS_MISMATCH: {\n phase: 'pre_send',\n template: 'The signing key does not belong to the expected account.',\n params: {},\n },\n INVALID_PRIVATE_KEY: {\n phase: 'pre_send',\n template: 'Invalid private key: {reason}.',\n params: { reason: INVALID_PRIVATE_KEY_REASONS },\n },\n SIGNING_FAILED: {\n phase: 'pre_send',\n template: 'Signing the {method} request failed ({reason}); nothing was sent.',\n params: { method: 'string', reason: SIGNING_FAILURE_REASONS },\n },\n KEY_PROVIDER_FAILED: {\n phase: 'pre_send',\n template: 'The signing key could not be fetched; nothing was sent.',\n params: {},\n },\n INVALID_SIGNING_HASH_LENGTH: {\n phase: 'pre_send',\n template: 'secp256k1 can only sign a 32-byte hash (got {length}).',\n params: { length: 'number' },\n },\n INVALID_WALLET_ADDRESS: {\n phase: 'pre_send',\n template: 'Invalid {field}: \"{value}\" is not an accepted wallet address form.',\n params: { field: 'string', value: 'string' },\n },\n INVALID_ETH_USER_REF_PREFIX: {\n phase: 'pre_send',\n template:\n 'Invalid {field}: \"{value}\" is not a GalaChain user reference. An eth| reference takes the 40 hex digits of the account with no 0x prefix; write it as \"{expected}\".',\n params: { field: 'string', value: 'string', expected: 'string' },\n },\n INVALID_DECIMAL: {\n phase: 'pre_send',\n template: 'Invalid decimal quantity: {value}',\n params: { value: 'string' },\n },\n\n // ------------------------------------------------------------------------- personal-sign DTOs\n PERSONAL_SIGN_NOT_JSON: {\n phase: 'pre_send',\n template: 'Personal-sign DTO is not valid JSON',\n params: {},\n },\n PERSONAL_SIGN_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Personal-sign DTO must be a JSON object',\n params: {},\n },\n PERSONAL_SIGN_BAD_PREFIX: {\n phase: 'pre_send',\n template: 'Personal-sign DTO prefix is not an EIP-191 \"Ethereum Signed Message\" header',\n params: {},\n },\n PERSONAL_SIGN_ENVELOPE_FIELDS: {\n phase: 'pre_send',\n template: 'Personal-sign DTO carries signing-envelope field(s): {fields}',\n params: { fields: 'string' },\n },\n PERSONAL_SIGN_NOT_CANONICAL: {\n phase: 'pre_send',\n template: 'Personal-sign DTO is not in canonical serialized form',\n params: {},\n },\n\n // ------------------------------------------------------------------ EIP-712 payload derivation\n EIP712_NAME_COLLISION: {\n phase: 'pre_send',\n template: 'Name collisions are not supported when deriving EIP-712 types ({name}).',\n params: { name: 'string' },\n },\n EIP712_UNSUPPORTED_VALUE: {\n phase: 'pre_send',\n template: 'Unsupported EIP-712 value of type {valueType}.',\n params: { valueType: 'string' },\n },\n\n // ----------------------------------------------------------------------------- EIP-712 typed data\n TYPED_DATA_NOT_STRING: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be a string',\n params: { what: 'string' },\n },\n TYPED_DATA_UNPAIRED_SURROGATE: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} has an unpaired surrogate',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_HEX_BYTES: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be an even-length 0x hex string',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_SAFE_INTEGER: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be a safe integer',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_INTEGER: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be an integer',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_BOOLEAN: {\n phase: 'pre_send',\n template: 'Invalid typed data: bool must be a boolean',\n params: {},\n },\n TYPED_DATA_BAD_ADDRESS: {\n phase: 'pre_send',\n template: 'Invalid typed data: address must be 0x followed by 40 hex digits',\n params: {},\n },\n TYPED_DATA_BAD_CHECKSUM: {\n phase: 'pre_send',\n template: 'Invalid typed data: address has a bad checksum',\n params: {},\n },\n TYPED_DATA_BYTES_LENGTH: {\n phase: 'pre_send',\n template: 'Invalid typed data: {type} must be exactly {width} bytes',\n params: { type: 'string', width: 'number' },\n },\n TYPED_DATA_OUT_OF_BOUNDS: {\n phase: 'pre_send',\n template: 'Invalid typed data: value out of bounds for {type}',\n params: { type: 'string' },\n },\n TYPED_DATA_UNSUPPORTED_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: unsupported type \"{type}\"',\n params: { type: 'string' },\n },\n TYPED_DATA_FIELDS_NOT_LIST: {\n phase: 'pre_send',\n template: 'Invalid typed data: type {typeName} must be a list of fields',\n params: { typeName: 'string' },\n },\n TYPED_DATA_FIELD_MALFORMED: {\n phase: 'pre_send',\n template: 'Invalid typed data: type {typeName} has a field without a string name and type',\n params: { typeName: 'string' },\n },\n TYPED_DATA_INVALID_FIELD_NAME: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid field name \"{name}\"',\n params: { name: 'string' },\n },\n TYPED_DATA_DUPLICATE_FIELD: {\n phase: 'pre_send',\n template: 'Invalid typed data: duplicate field \"{name}\" in {typeName}',\n params: { name: 'string', typeName: 'string' },\n },\n TYPED_DATA_INVALID_TYPE_NAME: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid type name \"{name}\"',\n params: { name: 'string' },\n },\n TYPED_DATA_CIRCULAR_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: circular type reference in {typeName}',\n params: { typeName: 'string' },\n },\n TYPED_DATA_UNKNOWN_FIELD_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: unknown type \"{type}\" in {typeName}',\n params: { type: 'string', typeName: 'string' },\n },\n TYPED_DATA_NO_PRIMARY_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: missing primary type',\n params: {},\n },\n TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: ambiguous primary types or unused types ({roots})',\n params: { roots: 'string' },\n },\n TYPED_DATA_ARRAY_EXPECTED: {\n phase: 'pre_send',\n template: 'Invalid typed data: {type} array value must be an array',\n params: { type: 'string' },\n },\n TYPED_DATA_ARRAY_LENGTH_MISMATCH: {\n phase: 'pre_send',\n template: 'Invalid typed data: array length mismatch',\n params: {},\n },\n TYPED_DATA_STRUCT_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Invalid typed data: {typeName} value must be an object',\n params: { typeName: 'string' },\n },\n TYPED_DATA_MISSING_FIELD: {\n phase: 'pre_send',\n template: 'Invalid typed data: {typeName} value is missing field \"{field}\"',\n params: { typeName: 'string', field: 'string' },\n },\n TYPED_DATA_DOMAIN_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Invalid typed data: domain must be an object',\n params: {},\n },\n TYPED_DATA_INVALID_DOMAIN_KEY: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid typed-data domain key {key}',\n params: { key: 'string' },\n },\n\n // ---------------------------------------------------------------------------------- unique keys\n INVALID_UNIQUE_KEY: {\n phase: 'pre_send',\n template:\n 'The uniqueKey \"{uniqueKey}\" must be 1-128 characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".',\n params: { uniqueKey: 'string' },\n },\n INVALID_UNIQUE_KEY_PREFIX: {\n phase: 'pre_send',\n template:\n 'uniqueKeyPrefix \"{uniqueKeyPrefix}\" must be at most {maxLength} characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".',\n params: { uniqueKeyPrefix: 'string', maxLength: 'number' },\n },\n CSPRNG_UNAVAILABLE: {\n phase: 'pre_send',\n template:\n 'No cryptographically secure random source (globalThis.crypto.getRandomValues) is available to mint a uniqueKey or a new wallet; install a getRandomValues polyfill (react-native-get-random-values on Hermes).',\n params: {},\n },\n\n // ----------------------------------------------------------------------------- gateway writes\n INVALID_WRITES_OPTION: {\n phase: 'pre_send',\n template: 'GatewayWrites option {option} is missing or is not of the expected type.',\n params: { option: GATEWAY_WRITES_OPTIONS },\n },\n INVALID_QUANTITY: {\n phase: 'pre_send',\n template:\n '{field} must be a positive decimal number of whole tokens, written as a string (got \"{value}\").',\n params: { field: 'string', value: 'string' },\n },\n INVALID_TOKEN_REFERENCE: {\n phase: 'pre_send',\n template: 'Invalid token reference {field}: {reason}.',\n params: { field: 'string', reason: INVALID_TOKEN_REFERENCE_REASONS },\n },\n INVALID_TOKEN_BATCH: {\n phase: 'pre_send',\n template: '{method} takes 1 to {max} tokens (got {count}).',\n params: { method: 'string', count: 'number', max: 'number' },\n },\n INVALID_LOCK_EXPIRES: {\n phase: 'pre_send',\n template:\n 'expires must be a non-negative whole number of epoch milliseconds, 0 for none (got {value}).',\n params: { value: 'string' },\n },\n INVALID_LOCK_NAME: {\n phase: 'pre_send',\n template: 'The lock name must be a string (got a {valueType}).',\n params: { valueType: 'string' },\n },\n NO_TOKEN_NAME_RESOLVER: {\n phase: 'pre_send',\n template:\n 'The token name \"{tokenName}\" cannot be resolved: no tokenNameResolver is configured. Pass its tokenClassKey instead.',\n params: { tokenName: 'string' },\n },\n TOKEN_NAME_RESOLUTION_FAILED: {\n phase: 'pre_send',\n template:\n 'The token name \"{tokenName}\" could not be resolved to a token class key; nothing was sent.',\n params: { tokenName: 'string' },\n },\n GATEWAY_WRITE_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'The outcome of {method} is unknown ({reason}): the request may have reached the gateway. Check the write by its uniqueKey before sending it again.',\n params: { method: 'string', reason: GATEWAY_WRITE_OUTCOME_UNKNOWN_REASONS },\n },\n GATEWAY_HTTP_ERROR: {\n phase: 'post_send',\n template: 'The gateway answered {method} with HTTP {status}.',\n params: { method: 'string', status: 'number', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n GATEWAY_WRITE_REJECTED: {\n phase: 'post_send',\n template: 'GalaChain rejected {method} (Status {chainStatus}, error key \"{errorKey}\").',\n params: {\n method: 'string',\n chainStatus: 'number',\n errorKey: 'string',\n serverMessage: 'string',\n },\n unrendered: ['serverMessage'],\n },\n GATEWAY_RESPONSE_INVALID: {\n phase: 'post_send',\n template:\n 'The gateway answered {method} with something that is not a GalaChain result; the write may have been applied.',\n params: { method: 'string' },\n },\n\n // ------------------------------------------------------------------------------ gateway reads\n INVALID_READS_OPTION: {\n phase: 'pre_send',\n template: 'GatewayReads option {option} is missing or is not of the expected type.',\n params: { option: GATEWAY_READS_OPTIONS },\n },\n INVALID_PAGE_REQUEST: {\n phase: 'pre_send',\n template:\n '{field} is not valid for a paginated read (got {value}): a page size or page count is a whole number from 1 to 10000, a bookmark a string.',\n params: { field: PAGE_REQUEST_FIELDS, value: 'string' },\n },\n GATEWAY_READ_REJECTED: {\n phase: 'post_send',\n template: 'GalaChain refused {method} (Status {chainStatus}, error key \"{errorKey}\").',\n params: {\n method: 'string',\n chainStatus: 'number',\n errorKey: 'string',\n serverMessage: 'string',\n },\n unrendered: ['serverMessage'],\n },\n GATEWAY_READ_RESPONSE_INVALID: {\n phase: 'post_send',\n template: 'The gateway answered {method} with something that is not a usable GalaChain result.',\n params: { method: 'string' },\n },\n TOKEN_CLASS_NOT_FOUND: {\n phase: 'post_send',\n template: 'GalaChain has no token class {tokenClassKey}.',\n params: { tokenClassKey: 'string' },\n },\n PAGINATION_LIMIT_EXCEEDED: {\n phase: 'post_send',\n template:\n 'Reading every page of {method} takes more than {maxPages} pages; narrow the filter or raise maxPages.',\n params: { method: 'string', maxPages: 'number' },\n },\n\n // ------------------------------------------------------------- wallet providers (`./providers`)\n WALLET_NOT_CONNECTED: {\n phase: 'pre_send',\n template: 'The wallet is not connected ({reason}): connect it before {operation}.',\n params: { reason: WALLET_NOT_CONNECTED_REASONS, operation: 'string' },\n },\n WALLET_CONNECTION_FAILED: {\n phase: 'pre_send',\n template: 'Connecting to the wallet failed ({reason}).',\n params: { reason: WALLET_CONNECTION_FAILURE_REASONS },\n },\n INVALID_WALLET_PROVIDER_CONFIG: {\n phase: 'pre_send',\n template: 'A wallet provider cannot be built without {missing}.',\n params: { missing: WALLET_PROVIDER_CONFIG_MISSING },\n },\n PRIVATE_KEY_NOT_ACCESSIBLE: {\n phase: 'pre_send',\n template:\n 'This wallet provider signs in the wallet and cannot give out a private key; only a PrivateKeyProvider holds one.',\n params: {},\n },\n\n // ----------------------------------------------------------------------------- wallet helpers\n INVALID_WALLET_INPUT: {\n phase: 'pre_send',\n template:\n 'The wallet input was refused ({reason}): give a private key (64 hex digits) or a 12- or 24-word mnemonic.',\n params: { reason: WALLET_INPUT_PROBLEMS },\n },\n\n // ------------------------------------------------------------------------ bridge (`./bridge`)\n INVALID_BRIDGE_AMOUNT: {\n phase: 'pre_send',\n template: 'The bridge amount \"{value}\" was refused ({reason}).',\n params: { value: 'string', reason: BRIDGE_AMOUNT_PROBLEMS },\n },\n UNSUPPORTED_BRIDGE_TOKEN: {\n phase: 'pre_send',\n template: '{symbol} cannot be bridged with {network}.',\n params: { network: 'string', symbol: 'string' },\n },\n BRIDGE_NOT_CONFIGURED: {\n phase: 'pre_send',\n template:\n '{network} bridging is not configured: give the bridge a {network} private key (ethereumPrivateKey / solanaPrivateKey).',\n params: { network: BRIDGE_NETWORKS },\n },\n INVALID_TRANSACTION_HASH: {\n phase: 'pre_send',\n template: '\"{value}\" is not a {network} transaction hash.',\n params: { network: BRIDGE_NETWORKS, value: 'string' },\n },\n INVALID_BRIDGE_OPTION: {\n phase: 'pre_send',\n template: 'The bridge option {option} is missing or out of range.',\n params: { option: 'string' },\n },\n BRIDGE_RESPONSE_INVALID: {\n phase: 'post_send',\n template:\n 'GalaConnect answered {method} without a usable {missing}; the request may have been accepted.',\n params: { method: 'string', missing: 'string' },\n },\n BRIDGE_READ_RESPONSE_INVALID: {\n phase: 'post_send',\n template: 'GalaConnect answered {method} with something that is not a usable result.',\n params: { method: 'string' },\n },\n BRIDGE_WRITE_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'The outcome of {method} is unknown: the request failed in transit and may have reached GalaConnect. Check it before sending it again.',\n params: { method: 'string' },\n },\n GALACONNECT_HTTP_ERROR: {\n phase: 'post_send',\n template: 'GalaConnect answered {method} with HTTP {status}.',\n params: { method: 'string', status: 'number', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n BRIDGE_TOKEN_NOT_FOUND: {\n phase: 'post_send',\n template: 'GalaConnect has no verified bridge configuration for {symbol}.',\n params: { symbol: 'string' },\n },\n TOKEN_NOT_WRAPPABLE: {\n phase: 'post_send',\n template: '{tokenId} cannot be wrapped or unwrapped ({reason}).',\n params: { tokenId: 'string', reason: WRAP_REFUSAL_REASONS },\n },\n INVALID_WRAP_DIRECTION: {\n phase: 'pre_send',\n template:\n 'Cannot {direction} {symbol}: it is on the wrong channel for it (use the other direction).',\n params: { symbol: 'string', direction: WRAP_DIRECTIONS },\n },\n BRIDGE_REQUEST_REJECTED: {\n phase: 'post_send',\n template: 'GalaChain refused {method} (Status {chainStatus}, error key \"{errorKey}\").',\n params: {\n method: 'string',\n chainStatus: 'number',\n errorKey: 'string',\n serverMessage: 'string',\n },\n unrendered: ['serverMessage'],\n },\n BRIDGE_OUT_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'GalaConnect accepted the bridge-out request, which may have locked the tokens, then the bridge-out failed at {step}. Check it before bridging again.',\n params: { step: BRIDGE_OUT_STEPS, bridgeRequestId: 'string' },\n unrendered: ['bridgeRequestId'],\n },\n BRIDGE_DEPOSIT_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'The {network} bridge deposit may have been sent, then its {step} failed. Check the deposit before sending another.',\n params: { network: BRIDGE_NETWORKS, step: BRIDGE_DEPOSIT_STEPS, transactionHash: 'string' },\n unrendered: ['transactionHash'],\n },\n BRIDGE_CHAIN_READ_FAILED: {\n phase: 'post_send',\n template: 'The {network} read {call} failed or answered something unusable; nothing was sent.',\n params: { network: BRIDGE_NETWORKS, call: 'string' },\n },\n INSUFFICIENT_BRIDGE_BALANCE: {\n phase: 'pre_send',\n template: 'The {network} balance of {symbol} is {available}; the bridge needs {needed}.',\n params: { network: BRIDGE_NETWORKS, symbol: 'string', needed: 'string', available: 'string' },\n },\n BRIDGE_STATUS_TIMEOUT: {\n phase: 'in_flight',\n template:\n 'The bridge transaction did not reach a final status within {timeoutMs} ms (last status {lastStatus}); it may still complete.',\n params: { transactionHash: 'string', timeoutMs: 'number', lastStatus: 'number' },\n unrendered: ['transactionHash'],\n },\n\n // ------------------------------------------------------------------- React context (`./react`)\n WALLET_CONTEXT_MISSING: {\n phase: 'pre_send',\n template: 'The wallet hooks and the wallet context need a WalletProvider above them.',\n params: {},\n },\n} as const satisfies Record<string, GalaErrorCatalogEntry>;\n\n/** Every error code the core SDK can throw. */\nexport type GalaErrorCode = keyof typeof GALA_ERROR_CATALOG;\n\ninterface KindToType {\n string: string;\n number: number;\n boolean: boolean;\n}\n\n/** The value type of a param kind: a primitive, or the union of a closed set's members. */\ntype ParamValue<K> = K extends readonly (infer Member)[]\n ? Member\n : K extends keyof KindToType\n ? KindToType[K]\n : never;\n\n/**\n * The named params of code `C` of ANY catalog object (`typeof SOME_CATALOG`): a flat object of\n * primitives (or closed string tokens). A product SDK derives its own params type from its\n * catalog with it, so every catalog types its params the same way.\n */\nexport type ErrorParamsOf<\n Catalog extends Readonly<Record<string, GalaErrorCatalogEntry>>,\n C extends keyof Catalog,\n> = {\n readonly [P in keyof Catalog[C]['params']]: ParamValue<Catalog[C]['params'][P]>;\n};\n\n/** The named params of one core error code. */\nexport type GalaErrorParams<C extends GalaErrorCode> = ErrorParamsOf<typeof GALA_ERROR_CATALOG, C>;\n\n/**\n * The English template of every core error code, `{placeholder}` markers included. An optional\n * seed or fallback for an app's own translations; the SDK's `message` is generated from it. A\n * product SDK exports the templates of its own codes next to it.\n */\nexport const galaErrorTemplates: { readonly [C in GalaErrorCode]: string } = Object.fromEntries(\n Object.entries(GALA_ERROR_CATALOG).map(([code, entry]) => [code, entry.template]),\n) as { readonly [C in GalaErrorCode]: string };\n\nconst PLACEHOLDER = /\\{([A-Za-z0-9_]+)\\}/gu;\n\n/** Fills a template's `{placeholders}` from `params`; an unknown placeholder is left as written. */\nexport function renderGalaErrorTemplate(\n template: string,\n params: Readonly<Record<string, unknown>>,\n): string {\n return template.replace(PLACEHOLDER, (whole, name: string) => {\n const value = params[name];\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : whole;\n });\n}\n\n/** The placeholder names a template uses, in order of first appearance. */\nexport function templatePlaceholders(template: string): string[] {\n return [...new Set([...template.matchAll(PLACEHOLDER)].map((match) => match[1] as string))];\n}\n","import type { GALA_ERROR_CATALOG, GalaErrorCode } from './error_catalog.js';\n\n/**\n * The phase of every core catalog code, WITHOUT the catalog. A failure guard (a product SDK's\n * `classifyFailure`, `mayHaveBeenQueued`, ...) needs only a code's phase, and the catalog's English\n * templates are several kB: reading the phase from here keeps an app shell that imports a guard\n * from loading them. The catalog entry is still where a code is declared; this table is checked\n * against it AT COMPILE TIME, in both directions (a missing code, an extra code or a different\n * phase is a type error), so the two cannot drift. A product SDK keeps the same kind of table for\n * its own codes.\n */\nexport const GALA_ERROR_PHASE_BY_CODE = {\n REQUEST_TIMEOUT: 'in_flight',\n TRANSPORT_ERROR: 'in_flight',\n INVALID_TIMEOUT: 'pre_send',\n GALA_WALLET_NOT_AVAILABLE: 'pre_send',\n WALLET_UNAVAILABLE: 'pre_send',\n MALFORMED_WALLET_REQUEST: 'pre_send',\n UNSUPPORTED_WALLET_METHOD: 'pre_send',\n INVALID_SIGNATURE: 'pre_send',\n INVALID_CHAIN_ID: 'pre_send',\n SIGNER_ADDRESS_MISMATCH: 'pre_send',\n INVALID_PRIVATE_KEY: 'pre_send',\n SIGNING_FAILED: 'pre_send',\n KEY_PROVIDER_FAILED: 'pre_send',\n INVALID_SIGNING_HASH_LENGTH: 'pre_send',\n INVALID_WALLET_ADDRESS: 'pre_send',\n INVALID_ETH_USER_REF_PREFIX: 'pre_send',\n INVALID_DECIMAL: 'pre_send',\n PERSONAL_SIGN_NOT_JSON: 'pre_send',\n PERSONAL_SIGN_NOT_OBJECT: 'pre_send',\n PERSONAL_SIGN_BAD_PREFIX: 'pre_send',\n PERSONAL_SIGN_ENVELOPE_FIELDS: 'pre_send',\n PERSONAL_SIGN_NOT_CANONICAL: 'pre_send',\n EIP712_NAME_COLLISION: 'pre_send',\n EIP712_UNSUPPORTED_VALUE: 'pre_send',\n TYPED_DATA_NOT_STRING: 'pre_send',\n TYPED_DATA_UNPAIRED_SURROGATE: 'pre_send',\n TYPED_DATA_NOT_HEX_BYTES: 'pre_send',\n TYPED_DATA_NOT_SAFE_INTEGER: 'pre_send',\n TYPED_DATA_NOT_INTEGER: 'pre_send',\n TYPED_DATA_NOT_BOOLEAN: 'pre_send',\n TYPED_DATA_BAD_ADDRESS: 'pre_send',\n TYPED_DATA_BAD_CHECKSUM: 'pre_send',\n TYPED_DATA_BYTES_LENGTH: 'pre_send',\n TYPED_DATA_OUT_OF_BOUNDS: 'pre_send',\n TYPED_DATA_UNSUPPORTED_TYPE: 'pre_send',\n TYPED_DATA_FIELDS_NOT_LIST: 'pre_send',\n TYPED_DATA_FIELD_MALFORMED: 'pre_send',\n TYPED_DATA_INVALID_FIELD_NAME: 'pre_send',\n TYPED_DATA_DUPLICATE_FIELD: 'pre_send',\n TYPED_DATA_INVALID_TYPE_NAME: 'pre_send',\n TYPED_DATA_CIRCULAR_TYPE: 'pre_send',\n TYPED_DATA_UNKNOWN_FIELD_TYPE: 'pre_send',\n TYPED_DATA_NO_PRIMARY_TYPE: 'pre_send',\n TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE: 'pre_send',\n TYPED_DATA_ARRAY_EXPECTED: 'pre_send',\n TYPED_DATA_ARRAY_LENGTH_MISMATCH: 'pre_send',\n TYPED_DATA_STRUCT_NOT_OBJECT: 'pre_send',\n TYPED_DATA_MISSING_FIELD: 'pre_send',\n TYPED_DATA_DOMAIN_NOT_OBJECT: 'pre_send',\n TYPED_DATA_INVALID_DOMAIN_KEY: 'pre_send',\n INVALID_UNIQUE_KEY: 'pre_send',\n INVALID_UNIQUE_KEY_PREFIX: 'pre_send',\n CSPRNG_UNAVAILABLE: 'pre_send',\n INVALID_WRITES_OPTION: 'pre_send',\n INVALID_QUANTITY: 'pre_send',\n INVALID_TOKEN_REFERENCE: 'pre_send',\n INVALID_TOKEN_BATCH: 'pre_send',\n INVALID_LOCK_EXPIRES: 'pre_send',\n INVALID_LOCK_NAME: 'pre_send',\n NO_TOKEN_NAME_RESOLVER: 'pre_send',\n TOKEN_NAME_RESOLUTION_FAILED: 'pre_send',\n GATEWAY_WRITE_OUTCOME_UNKNOWN: 'in_flight',\n GATEWAY_HTTP_ERROR: 'post_send',\n GATEWAY_WRITE_REJECTED: 'post_send',\n GATEWAY_RESPONSE_INVALID: 'post_send',\n INVALID_READS_OPTION: 'pre_send',\n INVALID_PAGE_REQUEST: 'pre_send',\n GATEWAY_READ_REJECTED: 'post_send',\n GATEWAY_READ_RESPONSE_INVALID: 'post_send',\n TOKEN_CLASS_NOT_FOUND: 'post_send',\n PAGINATION_LIMIT_EXCEEDED: 'post_send',\n WALLET_NOT_CONNECTED: 'pre_send',\n WALLET_CONNECTION_FAILED: 'pre_send',\n INVALID_WALLET_PROVIDER_CONFIG: 'pre_send',\n PRIVATE_KEY_NOT_ACCESSIBLE: 'pre_send',\n INVALID_WALLET_INPUT: 'pre_send',\n INVALID_BRIDGE_AMOUNT: 'pre_send',\n UNSUPPORTED_BRIDGE_TOKEN: 'pre_send',\n BRIDGE_NOT_CONFIGURED: 'pre_send',\n INVALID_TRANSACTION_HASH: 'pre_send',\n INVALID_BRIDGE_OPTION: 'pre_send',\n BRIDGE_RESPONSE_INVALID: 'post_send',\n BRIDGE_READ_RESPONSE_INVALID: 'post_send',\n BRIDGE_WRITE_OUTCOME_UNKNOWN: 'in_flight',\n GALACONNECT_HTTP_ERROR: 'post_send',\n BRIDGE_TOKEN_NOT_FOUND: 'post_send',\n TOKEN_NOT_WRAPPABLE: 'post_send',\n INVALID_WRAP_DIRECTION: 'pre_send',\n BRIDGE_REQUEST_REJECTED: 'post_send',\n BRIDGE_OUT_OUTCOME_UNKNOWN: 'in_flight',\n BRIDGE_DEPOSIT_OUTCOME_UNKNOWN: 'in_flight',\n BRIDGE_CHAIN_READ_FAILED: 'post_send',\n INSUFFICIENT_BRIDGE_BALANCE: 'pre_send',\n BRIDGE_STATUS_TIMEOUT: 'in_flight',\n WALLET_CONTEXT_MISSING: 'pre_send',\n} as const satisfies {\n readonly [C in GalaErrorCode]: (typeof GALA_ERROR_CATALOG)[C]['phase'];\n};\n\n/** True for a code the CORE catalog defines (a product SDK's own codes are not). */\nexport function isGalaCatalogCode(code: string): code is GalaErrorCode {\n return Object.hasOwn(GALA_ERROR_PHASE_BY_CODE, code);\n}\n","/**\n * How far an operation had got when it failed, measured against the request it exists to send:\n * for a write, the POST that carries the signed DTO to the gateway; for a read, the GET.\n *\n * - `pre_send`: NOTHING was transmitted. Everything up to the request (validation, symbol\n * resolution, the signer, the wallet, a key provider) ran and failed, so no write can have been\n * queued. A write that failed `pre_send` is never \"maybe applied\".\n * - `in_flight`: the request left (or may have left) and no answer was read: a timeout, a broken\n * connection, a stream that dropped. For a write the outcome is unknown.\n * - `post_send`: an answer was read, or the write was already accepted: a refusal, an\n * acknowledgement that proves nothing, an unusable body, and every failure of a confirmation.\n *\n * Each catalog entry (core's and every product SDK's) declares the phase its code is thrown in; a\n * throw site where the same code can occur in another phase overrides it\n * (`GalaErrorContext.phase`). It is a typed property of every `GalaSDKError` (`error.phase`).\n *\n * This module has no imports, on purpose: it is the closed set of phases, shared by the catalogs,\n * the light phase tables (`error_phase_table.ts`) and the failure view.\n */\nexport const GALA_ERROR_PHASES = ['pre_send', 'in_flight', 'post_send'] as const;\n\n/** One member of {@link GALA_ERROR_PHASES}. */\nexport type GalaErrorPhase = (typeof GALA_ERROR_PHASES)[number];\n","/**\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","import { GALA_ERROR_BRAND } from '../utils/error_brand.js';\nimport {\n GALA_ERROR_CATALOG,\n renderGalaErrorTemplate,\n type GalaErrorCatalogEntry,\n type GalaErrorCode,\n type GalaErrorParams,\n} from './error_catalog.js';\nimport type { GalaErrorPhase } from './error_phases.js';\n\n/**\n * The facts of an error that are not placeholders of its message: where it happened and what the\n * server said. All optional; none is localized text.\n */\nexport interface GalaErrorContext {\n /** The HTTP status of the response that caused the error. */\n status?: number | undefined;\n /**\n * The response body: parsed JSON when the failing response had it, else the raw text (which\n * the error then exposes as {@link GalaSDKError.bodyText}).\n */\n body?: unknown;\n /** The URL the failing request went to. */\n url?: string | undefined;\n /** The `uniqueKey` of the write this error is about: the handle for `confirm()` and recovery. */\n uniqueKey?: string | undefined;\n /** The transaction id of the queued request, `null` when unknown. */\n requestTransactionId?: string | null | undefined;\n /** The transaction id of the apply, `null` when unknown. */\n applyTransactionId?: string | null | undefined;\n /** The block the apply landed in, `null` when unknown. */\n blockNumber?: number | null | undefined;\n /** How long to wait before retrying, from the server's `Retry-After`. */\n retryAfterMs?: number | undefined;\n /** The error that caused this one (a transport failure, a wallet rejection). */\n cause?: unknown;\n /**\n * The phase of THIS occurrence when it differs from the code's catalog phase (see\n * {@link GalaErrorPhase}): for example a product code that is `pre_send` from a local registry\n * but `post_send` when it is derived from a server answer.\n */\n phase?: GalaErrorPhase | undefined;\n /** True when the failing operation was on the shadow (dark) path; see {@link GalaSDKError.shadow}. */\n shadow?: boolean | undefined;\n /**\n * `false` for the failure of a READ (see {@link GalaSDKError.write}); anything else, including\n * absent, is a write (fail-closed). Ignored when `uniqueKey` is set: that is a write.\n */\n write?: boolean | undefined;\n /** The wallet's own code on the error a signer threw; see {@link GalaSDKError.walletCode}. */\n walletCode?: number | string | undefined;\n}\n\n/** What the params of ANY SDK error are: a flat object of primitives. */\nexport type GalaErrorParamsShape = Readonly<Record<string, string | number | boolean>>;\n\n/**\n * The params type of a CORE code, and `never` for any other string: constructing a `GalaSDKError`\n * itself with a code the core catalog does not define is a compile error. A product SDK's subclass\n * supplies its own params type for its codes.\n */\nexport type GalaParamsOf<C extends string> = C extends GalaErrorCode ? GalaErrorParams<C> : never;\n\n/** Reads the catalog entry of `code`, failing loudly for a code the catalog does not define. */\nfunction catalogEntry(\n catalog: Readonly<Record<string, GalaErrorCatalogEntry>>,\n code: string,\n): GalaErrorCatalogEntry {\n const entry = Object.hasOwn(catalog, code) ? catalog[code] : undefined;\n if (entry === undefined) {\n // Unreachable through the types (the code parameter is the catalog's own key union); a cast\n // that smuggles in a foreign code is a programming error, so it fails at the throw site.\n throw new TypeError(`${code} is not a code of this error class's catalog`);\n }\n return entry;\n}\n\n/**\n * Error raised by the SDKs for validation, signing, transport, gateway, chain, or transaction\n * failures. Every product SDK's error class (`GSwapSDKError`, ...) extends it, so\n * `error instanceof GalaSDKError` (or {@link isGalaError}) recognises an error from ANY of them.\n *\n * Branch on {@link code} (stable) and render {@link params} through your own localization.\n * {@link message} is English generated from the catalog template for logs and developers: it\n * is not stable and must never be shown to a user or matched on.\n *\n * The class reads a code's template and phase from its static {@link GalaSDKError.catalog}: the\n * core catalog here, core's plus a product's own codes on a product subclass. One code is defined\n * in exactly one catalog.\n */\nexport class GalaSDKError<C extends string = GalaErrorCode, P = GalaParamsOf<C>> extends Error {\n /**\n * The catalog this class reads templates and phases from. A product SDK's subclass overrides it\n * with an object holding core's codes AND its own (core's entries are never redefined there).\n */\n public static readonly catalog: Readonly<Record<string, GalaErrorCatalogEntry>> =\n GALA_ERROR_CATALOG;\n\n /** The stable, machine-readable code. */\n public readonly code: C;\n /** The named placeholders of the error: a flat object of primitives, safe to localize with. */\n public readonly params: P;\n /** The server's `Retry-After` in milliseconds (a rate-limited answer), when it sent one. */\n public readonly retryAfterMs: number | undefined;\n /** The HTTP status of the response that caused this error, when there was one. */\n public readonly status: number | undefined;\n /**\n * The response body parsed as JSON, when the failing response had one; `undefined` for a body\n * that was not JSON (see {@link bodyText}). Never part of {@link message}.\n */\n public readonly body: unknown;\n /**\n * The raw text of a failing response whose body was NOT JSON (a proxy's HTML 502, a WAF page,\n * an empty body). It is kept here for diagnostics and is never copied into {@link message},\n * so it cannot reach a user interface by accident.\n */\n public readonly bodyText: string | undefined;\n /** The URL the failing request went to, when there was one. */\n public readonly url: string | undefined;\n /** The `uniqueKey` of the write this error is about, when there is one. */\n public readonly uniqueKey: string | undefined;\n /** The transaction id of the queued request, when known. */\n public readonly requestTransactionId: string | null | undefined;\n /** The transaction id of the apply, when known. */\n public readonly applyTransactionId: string | null | undefined;\n /** The block the apply landed in, when known. */\n public readonly blockNumber: number | null | undefined;\n /**\n * How far the operation had got when this was thrown, against the request it exists to send\n * (see {@link GalaErrorPhase}): `pre_send` means NOTHING was transmitted, so a write that\n * failed this way cannot have been queued; `in_flight` means the request left and no answer was\n * read; `post_send` means an answer was read or the write was already accepted. Every catalog\n * code declares its phase, and a throw site can refine it. A product SDK's failure classifier\n * (gswap-sdk's `classifyFailure`, `isPreSendError`) folds it into its answers.\n */\n public readonly phase: GalaErrorPhase;\n /**\n * True when this error came from the shadow (dark) path of a product SDK (gswap-sdk's\n * `swapShadow`, `submitSwapShadow`, `ChainGateway.submitShadow`), whatever failed there. The\n * classification is the same as on the public path; this is how an app applies its own\n * dark-swap policy.\n */\n public readonly shadow: boolean;\n /**\n * Whether this failure is a WRITE's, as the guards read it: `false` only for the failure of a\n * READ (a quote, a list, a result read), which has no `uniqueKey` to confirm and nothing\n * pending, so a 5xx there is `transient` and retryable. It is `true` for everything else, and\n * always when {@link uniqueKey} is set. That is fail-closed: a failure that does not say it is a\n * read is judged a write, where a 5xx is `unknown` and never retried. Apps that carry an error\n * through their own wrapper copy this field next to `uniqueKey` (`FailureView.write`).\n */\n public readonly write: boolean;\n /**\n * On `SIGNING_FAILED`: the code the wallet put on the error its signer threw, when it set one: an\n * EIP-1193 / JSON-RPC number such as `4001` (the person declined) or `-32603`, or an ethers /\n * viem string such as `'ACTION_REJECTED'`. It is read from the `cause`'s own `code` and is\n * always a short primitive; `undefined` when the wallet sent none, and on every other code. It is\n * a typed field, not a param: it is data for an app's analytics or its own wallet-specific\n * wording, never part of `message`, and `params.reason` stays the stable thing to branch on.\n */\n public readonly walletCode: number | string | undefined;\n\n constructor(code: C, params: NoInfer<P>, context: GalaErrorContext = {}) {\n const entry = catalogEntry(new.target.catalog, code);\n super(\n renderGalaErrorTemplate(entry.template, params as Readonly<Record<string, unknown>>),\n context.cause === undefined ? undefined : { cause: context.cause },\n );\n this.name = 'GalaSDKError';\n this.code = code;\n this.params = params;\n this.retryAfterMs = context.retryAfterMs;\n this.status = context.status;\n this.body = typeof context.body === 'string' ? undefined : context.body;\n this.bodyText = typeof context.body === 'string' ? context.body : undefined;\n this.url = context.url;\n this.uniqueKey = context.uniqueKey;\n this.requestTransactionId = context.requestTransactionId;\n this.applyTransactionId = context.applyTransactionId;\n this.blockNumber = context.blockNumber;\n this.phase = context.phase ?? entry.phase;\n this.shadow = context.shadow ?? false;\n this.write =\n context.uniqueKey !== undefined && context.uniqueKey !== '' ? true : context.write !== false;\n this.walletCode = context.walletCode;\n }\n\n /**\n * The SDK error brand (`Symbol.for('@gala-chain/gala-core-sdk/error')`), always `true`, carried\n * by every product SDK's error class through inheritance. The dependency-free helpers\n * (`isWalletUserRejection`, `isGalaErrorLike`) recognise an SDK error by it instead of\n * `instanceof`, so they work across copies of the SDK and without importing this class. It lives\n * on the prototype: it is not an own property and is never copied or logged.\n */\n public get [GALA_ERROR_BRAND](): true {\n return true;\n }\n\n /**\n * True when the failure means \"that thing does not exist\" rather than \"something went wrong\":\n * an HTTP 404. A product SDK's subclass adds its own not-found codes (gswap-sdk: no pool, an\n * unknown token).\n */\n public get notFound(): boolean {\n return this.status === 404;\n }\n}\n\n/** Any thrown value that is a CORE SDK error, narrowed to the union of every core code. */\nexport type AnyGalaError = { [C in GalaErrorCode]: GalaSDKError<C> }[GalaErrorCode];\n\n/**\n * True when `value` is an SDK error (core's, or any product SDK's subclass) and, when `code` is\n * given, carries exactly that core code. With a code, `error.params` narrows to that code's\n * params. Without one it narrows only to \"an SDK error with some string code\": a product error's\n * code is not a core code, so it is not typed as one.\n *\n * @example\n * ```ts\n * if (isGalaError(error, 'INVALID_PRIVATE_KEY')) {\n * t(`errors.key.${error.params.reason}`);\n * }\n * ```\n */\nexport function isGalaError(value: unknown): value is GalaSDKError<string, GalaErrorParamsShape>;\nexport function isGalaError<C extends GalaErrorCode>(\n value: unknown,\n code: C,\n): value is GalaSDKError<C>;\nexport function isGalaError(value: unknown, code?: GalaErrorCode): boolean {\n return value instanceof GalaSDKError && (code === undefined || value.code === code);\n}\n\n/** Parse a response body, preserving non-JSON text for error reporting. */\nexport function parseJson(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n","/**\n * EIP-55 for the 40 hex digits of an Ethereum address, on `@noble/hashes` (no ethers): the one\n * place core computes the checksum casing, shared by the typed-data encoder (which refuses a bad\n * mixed-case address) and the gateway writes (which spell an `0x` account as `eth|<checksummed>`).\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\n\nconst textEncoder = new TextEncoder();\n\n/**\n * The EIP-55 casing of 40 hex digits (any case in, no `0x`): a letter is upper-case where the\n * matching nibble of keccak256(lower-case digits) is 8 or more. Byte-identical to ethers'\n * `getAddress(...).slice(2)` for every 40-digit input.\n */\nexport function eip55Digits(digits: string): string {\n const lower = digits.toLowerCase();\n const hash = keccak_256(textEncoder.encode(lower));\n let checksummed = '';\n for (let index = 0; index < lower.length; index += 1) {\n const nibble = ((hash[index >> 1] as number) >> (index % 2 === 0 ? 4 : 0)) & 0xf;\n const char = lower.charAt(index);\n checksummed += nibble >= 8 ? char.toUpperCase() : char;\n }\n return checksummed;\n}\n\n/**\n * True when 40 hex digits carry no checksum (all one case, as EIP-55 allows) or exactly the\n * EIP-55 one. A mixed-case address with any letter in the wrong case is a typo EIP-55 exists to\n * catch, and is refused by every caller.\n */\nexport function hasValidEip55Casing(digits: string): boolean {\n const mixedCase = /[A-F]/u.test(digits) && /[a-f]/u.test(digits);\n return !mixedCase || eip55Digits(digits) === digits;\n}\n\nconst ACCOUNT_DIGITS = /^(?:0x)?([0-9a-fA-F]{40})$/u;\n\n/**\n * An Ethereum account (`0x` plus 40 hex digits, or the 40 digits alone) as `0x` plus its EIP-55\n * checksummed digits, or `undefined` for anything else: another length or character, or a\n * mixed-case spelling whose casing is not the EIP-55 one (a typo EIP-55 exists to catch).\n * Byte-identical to ethers' `getAddress` for every value it accepts.\n *\n * @example\n * ```typescript\n * checksumEthereumAddress('0x70997970c51812dc3a010c7d01b50e0d17dc79c8');\n * // '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'\n * ```\n */\nexport function checksumEthereumAddress(value: string): string | undefined {\n const digits = ACCOUNT_DIGITS.exec(value)?.[1];\n return digits !== undefined && hasValidEip55Casing(digits)\n ? `0x${eip55Digits(digits)}`\n : undefined;\n}\n","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","/**\n * Genuine EIP-712 typed-data signing for the four v2 dex-contract operations, proven by a live\n * bisection against the staging chain to recover the `client|` identity correctly via\n * `eth_signTypedData_v4`, unlike `personal_sign` (which only ever resolves the bare `eth|` form;\n * see `BrowserWalletSigner`'s own doc comment). The field completers mirror the web app's\n * typed-data builders exactly. (Moved from gswap-sdk with the rest of the signing closure; the\n * four methods are dex-contract methods, the derivation is generic.)\n */\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\n\n/** EIP-712 `types`: each struct name mapped to its ordered `{ name, type }` fields. */\nexport type EIP712Types = Record<string, Array<{ name: string; type: string }>>;\n\n/**\n * Derives the EIP-712 `types` for a DTO from its runtime shape.\n *\n * The generated `types` travel with the signed payload and are what BOTH sides hash, so they\n * must enumerate EVERY field the chain-side DTO will carry. GalaChain refuses any signature\n * whose `types` leave a DTO field uncovered (`assertNoUnsignedFields`, the fix for the\n * 2026-08-18 unsigned-field-injection drain); when that happens signature recovery fails\n * outright and the chain reports \"Missing signerPublicKey or signerAddress field in dto\".\n */\nexport function generateEIP712Types(\n typeName: string,\n params: Record<string, unknown>,\n): EIP712Types {\n const types: EIP712Types = {};\n types[typeName] = [];\n\n // Every `name` this is ever called with (the top-level `typeName`, or a nested struct's own\n // name) is unconditionally assigned `types[name] = []` on the line immediately before any\n // recursive call that could reach here; TypeScript still types `types[name]` as\n // possibly-undefined (index-signature access), so the guard below stays for real type safety\n // even though no current call path can actually trigger it.\n function fieldsFor(name: string): Array<{ name: string; type: string }> {\n const fields = types[name];\n /* c8 ignore next */\n if (!fields) throw new Error(`Missing EIP-712 type definition for ${name}`);\n return fields;\n }\n\n function addField(\n name: string,\n fieldValue: unknown,\n parentTypeName: string,\n onlyGetType = false,\n ): string | undefined {\n if (Array.isArray(fieldValue)) {\n const type =\n fieldValue.length > 0 ? addField(name, fieldValue[0], parentTypeName, true) : 'string';\n if (!onlyGetType) fieldsFor(parentTypeName).push({ name, type: (type ?? name) + '[]' });\n } else if (typeof fieldValue === 'object' && fieldValue !== null) {\n if (types[name]) {\n throw new GalaSDKError('EIP712_NAME_COLLISION', { name });\n }\n types[name] = [];\n Object.entries(fieldValue).forEach(([key, value]) => {\n addField(key, value, name);\n });\n if (!onlyGetType) fieldsFor(parentTypeName).push({ name, type: name });\n } else {\n let eipType: string;\n switch (typeof fieldValue) {\n case 'string':\n eipType = 'string';\n break;\n case 'number':\n eipType = 'int256';\n break;\n case 'boolean':\n eipType = 'bool';\n break;\n case 'bigint':\n case 'symbol':\n case 'undefined':\n case 'function':\n case 'object':\n throw new GalaSDKError('EIP712_UNSUPPORTED_VALUE', { valueType: typeof fieldValue });\n }\n if (onlyGetType) {\n return eipType;\n }\n fieldsFor(parentTypeName).push({ name, type: eipType });\n }\n return undefined;\n }\n\n Object.entries(params).forEach(([key, value]) => {\n addField(key, value, typeName);\n });\n\n return types;\n}\n\n/** The EIP-712 domain carried by a signed payload: GalaChain only uses `name` and `chainId`. */\nexport interface EIP712DomainValue {\n name: string;\n chainId: number;\n}\n\n/**\n * Builds the EIP-712 domain from the wallet's LIVE `eth_chainId` result: a wallet hashes whatever\n * domain it is handed, and MetaMask refuses a `chainId` that differs from its active network, so\n * a hardcoded `1` breaks every wallet that is not on Mainnet.\n * The backend recovers the signer from the `domain` the payload carries (live-proven for chain\n * ids 1, 56 and 11155111), so following the wallet is correct on every network.\n *\n * @param chainId - The raw `eth_chainId` result: a `0x` hex string (the JSON-RPC form) or an integer.\n * @param name - The domain name the deployment requires (`GALA_CHAIN_ENVIRONMENTS[env].eip712DomainName`);\n * `'ethereum'`, what every signer has always signed, when absent.\n * @throws GalaSDKError (`INVALID_CHAIN_ID`) when the wallet answers with anything else.\n */\nexport function eip712DomainFor(chainId: unknown, name = 'ethereum'): EIP712DomainValue {\n const parsed =\n typeof chainId === 'string' && /^0x[0-9a-fA-F]+$/u.test(chainId)\n ? Number(chainId)\n : typeof chainId === 'number'\n ? chainId\n : Number.NaN;\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new GalaSDKError('INVALID_CHAIN_ID', {\n chainId:\n typeof chainId === 'string' || typeof chainId === 'number'\n ? String(chainId)\n : typeof chainId,\n });\n }\n return { name, chainId: parsed };\n}\n\n/**\n * The four v2 operations proven to recover the signer correctly via genuine EIP-712: `RequestTrade`\n * never had the problem (one numeric field). `AddLiquidity`/`RemoveLiquidity`/\n * `CollectPositionFees` each need their `types` completed with a handful of fields their real\n * server-side DTO always carries — see the `complete*Fields` functions below. `CreatePool` is a\n * genuinely different, unsolved problem (nested `TokenClassKey` structs, not a flat\n * missing-field gap) and is NOT in this set — callers must keep using `personal-sign` for it.\n */\nexport const EIP712_CAPABLE_METHODS: ReadonlySet<string> = new Set([\n 'RequestTrade',\n 'AddLiquidity',\n 'RemoveLiquidity',\n 'CollectPositionFees',\n]);\n\n/**\n * Every `complete*Fields` function below shares the same two live-proven rules:\n * 1. Numeric completeness fields MUST be JS `number`, never numeric strings —\n * `generateEIP712Types` infers a field's Solidity type from `typeof`, and declaring one as\n * EIP-712 `string` instead of `int256` breaks recovery identically to omitting the field\n * entirely (verified live on AddLiquidity: `amount0Min: '0'` fails with the exact same\n * \"Missing signerPublicKey\" error as `amount0Min` being absent; `amount0Min: 0` succeeds).\n * 2. `positionId` has no such constraint — an empty string works, and does not target an\n * existing position (`positionId: ''` created a fresh position on AddLiquidity, not an add\n * to position id `''`; on RemoveLiquidity/CollectPositionFees the real position is still\n * resolved from `token0`/`token1`/`fee`/`tickLower`/`tickUpper`, not from this field).\n */\nfunction numericOr0(dto: Record<string, unknown>, field: string): number {\n return typeof dto[field] === 'number' ? dto[field] : 0;\n}\n\n/**\n * `AddLiquidity`'s real server-side DTO always carries `amount0Desired`/`amount0Min`/\n * `amount1Desired`/`amount1Min`/`positionId` once reconstructed, regardless of which deposit\n * convention the caller used (`Positions.addLiquidityByTicks` only ever sends\n * `depositQuantityToken0`/`depositQuantityToken1`). Proven empirically by bisection: none of the\n * five alone fixes recovery, all five together does (live 201, tx `407d9b24...`, block\n * `2429022`).\n */\nfunction completeAddLiquidityFields(dto: Record<string, unknown>): Record<string, unknown> {\n return {\n ...dto,\n amount0Desired: numericOr0(dto, 'amount0Desired'),\n amount0Min: numericOr0(dto, 'amount0Min'),\n amount1Desired: numericOr0(dto, 'amount1Desired'),\n amount1Min: numericOr0(dto, 'amount1Min'),\n positionId: dto['positionId'] ?? '',\n };\n}\n\n/**\n * `RemoveLiquidity`'s real server-side DTO always carries `amount`/`amount0Min`/`amount1Min`/\n * `positionId` — `Positions.removeLiquidity` only ever sends a `withdrawalQuantityTokenX` (or\n * neither, for a full close). Proven empirically: every subset of these four fails, all four\n * together succeeds (live, random-signer probe — recovery confirmed by the response moving from\n * \"Missing signerPublicKey\" to a genuine position-not-found 404).\n */\nfunction completeRemoveLiquidityFields(dto: Record<string, unknown>): Record<string, unknown> {\n return {\n ...dto,\n amount: numericOr0(dto, 'amount'),\n amount0Min: numericOr0(dto, 'amount0Min'),\n amount1Min: numericOr0(dto, 'amount1Min'),\n positionId: dto['positionId'] ?? '',\n };\n}\n\n/**\n * `CollectPositionFees`'s real server-side DTO always carries `amount0Requested`/\n * `amount1Requested`/`positionId` — `Positions.collectPositionFees` sends only the five identity\n * fields. Proven empirically the same way as `completeRemoveLiquidityFields`.\n */\nfunction completeCollectPositionFeesFields(dto: Record<string, unknown>): Record<string, unknown> {\n return {\n ...dto,\n amount0Requested: numericOr0(dto, 'amount0Requested'),\n amount1Requested: numericOr0(dto, 'amount1Requested'),\n positionId: dto['positionId'] ?? '',\n };\n}\n\nexport const EIP712_FIELD_COMPLETERS: Readonly<\n Record<string, (dto: Record<string, unknown>) => Record<string, unknown>>\n> = {\n AddLiquidity: completeAddLiquidityFields,\n RemoveLiquidity: completeRemoveLiquidityFields,\n CollectPositionFees: completeCollectPositionFeesFields,\n};\n\n/**\n * Completes a DTO's fields for EIP-712 signing (a no-op for methods with no known gap, e.g.\n * `RequestTrade`) and derives its `types`. Exported separately from the signing call itself so tests\n * can assert on the exact payload without needing a live provider.\n */\nexport function buildEIP712Payload(\n methodName: string,\n dto: Record<string, unknown>,\n): { completedDto: Record<string, unknown>; types: EIP712Types } {\n const completer = EIP712_FIELD_COMPLETERS[methodName];\n const completedDto = completer ? completer(dto) : dto;\n const types = generateEIP712Types(methodName, completedDto);\n return { completedDto, types };\n}\n","/**\n * SDK-owned signing primitives.\n *\n * Everything the SDK needs to produce a GalaChain signature lives here, with no dependency on\n * `@gala-chain/api` (which drags `secp256k1` native bindings, `reflect-metadata`, `class-validator`\n * and its own `bignumber.js` major into every consumer). The only runtime dependencies are the\n * audited, pure-JS `@noble/curves` (secp256k1) and `@noble/hashes` (keccak256), which run\n * unchanged in browsers, MV3 service workers, Node and React Native/Hermes.\n *\n * Every function here is pinned byte-for-byte to the signatures produced by `@gala-chain/api`\n * (`serialize`, `signatures.getSignature`), `@gala-chain/connect`, the Gala Wallet extension and\n * the gSwap web app by the golden-vector suite in `tests/signing-golden.test.ts`.\n */\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\nimport type { InvalidPrivateKeyReason } from '../classes/error_catalog.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\n\nconst textEncoder = new TextEncoder();\n\nfunction toDeterministicNode(node: unknown): unknown {\n if (node === null || node === undefined) return node;\n if (node instanceof RegExp) return node.toString();\n const candidate = node as { toJSON?: unknown };\n return typeof candidate.toJSON === 'function'\n ? (Reflect.apply(candidate.toJSON, node, []) as unknown)\n : node;\n}\n\nfunction deterministicNode(rawNode: unknown): string | undefined {\n const node = toDeterministicNode(rawNode);\n if (node === undefined) return undefined;\n if (typeof node !== 'object' || node === null) return JSON.stringify(node);\n\n if (Array.isArray(node)) {\n const items = (node as unknown[]).map((item) => deterministicNode(item) ?? 'null');\n return `[${items.join(',')}]`;\n }\n\n const record = node as Record<string, unknown>;\n const members: string[] = [];\n for (const key of Object.keys(record).sort()) {\n const value = deterministicNode(record[key]);\n if (value === undefined) continue;\n members.push(`${JSON.stringify(key)}:${value}`);\n }\n return `{${members.join(',')}}`;\n}\n\n/**\n * GalaChain's deterministic JSON: object keys sorted (UTF-16 code-unit order) at every depth, no\n * whitespace, `undefined`/function members dropped, `toJSON()` honored. Byte-identical to\n * `serialize` from `@gala-chain/api` / `json-stringify-deterministic` for every JSON-shaped\n * value, which is all a DTO ever is.\n *\n * @throws TypeError for circular structures and BigInt values (as `JSON.stringify` does) and\n * when the value itself has no JSON representation (`undefined`, a function, a symbol).\n */\nexport function serialize(value: unknown): string {\n // Same cycle/BigInt guard json-stringify-deterministic runs before walking the value.\n JSON.stringify(value);\n const result = deterministicNode(value);\n if (result === undefined) {\n throw new TypeError('Cannot serialize a value with no JSON representation.');\n }\n return result;\n}\n\n/**\n * The exact string GalaChain hashes for a DTO: the (optional, string) `prefix` field PREPENDED to\n * the deterministic serialization of the DTO WITHOUT `signature`, `multisig`, `trace` and `prefix`.\n * Equivalent to `@gala-chain/api` 3.x `getPayloadToSign` for every non-EIP-712 DTO.\n */\nexport function getPayloadToSign(dto: Record<string, unknown>): string {\n const { prefix, ...rest } = dto;\n delete rest['signature'];\n delete rest['multisig'];\n delete rest['trace'];\n const head = typeof prefix === 'string' ? prefix : '';\n return head + serialize(rest);\n}\n\n// Built via String.fromCharCode rather than a literal escape ON PURPOSE: a literal control byte in\n// source is invisible and fragile under editors/diffs/copy-paste; this keeps the source ordinary.\nconst ETHEREUM_SIGNED_MESSAGE = String.fromCharCode(0x19) + 'Ethereum Signed Message:\\n';\n\n/**\n * The EIP-191 header for `message`: `\"\\x19Ethereum Signed Message:\\n\"` + the message's UTF-8 BYTE\n * length. This is what a wallet's `personal_sign` prepends, and what the chain recomputes when it\n * recovers a personal-signed DTO.\n */\nexport function calculatePersonalSignPrefix(message: string): string {\n return ETHEREUM_SIGNED_MESSAGE + String(textEncoder.encode(message).length);\n}\n\n/**\n * The EIP-191 header for `serialize(dto)` (any `prefix` already on the DTO is ignored). This is\n * deliberately the same string the signers hand a wallet to sign, so the header's length can never\n * disagree with the signed message. Wallet-neutral: it is the value both a browser wallet's\n * `personal_sign` and Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepend.\n */\nexport function personalSignPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n return calculatePersonalSignPrefix(serialize(withoutPrefix));\n}\n\n/**\n * The `@gala-chain/connect`-style prefix the gSwap web app puts in the body of an EIP-712 write: the\n * EIP-191 header whose number counts the prefix string ITSELF plus the body (the UTF-8 length of\n * `getPayloadToSign({ ...dto, prefix })`), found by fixpoint because adding the prefix changes the\n * length (a body of 99 bytes settles on 101).\n *\n * It is NOT a personal-sign prefix (a personal-sign write with this value recovers a phantom\n * signer; use `personalSignPrefixFor`). Under EIP-712 the field is an untyped extra that the\n * typed-data hash ignores and the backend recomputes, so it only exists to keep the submitted\n * body byte-identical to what the gSwap web app has always sent.\n */\nexport function fixpointPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n let payloadLength = textEncoder.encode(getPayloadToSign(withoutPrefix)).length;\n let prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n let previousLength = -1;\n while (payloadLength !== previousLength) {\n previousLength = payloadLength;\n prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n payloadLength = textEncoder.encode(getPayloadToSign({ ...withoutPrefix, prefix })).length;\n }\n return prefix;\n}\n\nfunction invalidPrivateKey(reason: InvalidPrivateKeyReason): GalaSDKError<'INVALID_PRIVATE_KEY'> {\n return new GalaSDKError('INVALID_PRIVATE_KEY', { reason });\n}\n\nconst BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nfunction decodeBase64(input: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(input) || input.length % 4 !== 0) return undefined;\n const unpadded = input.replace(/=+$/u, '');\n const bytes: number[] = [];\n let buffer = 0;\n let bits = 0;\n for (const char of unpadded) {\n buffer = (buffer << 6) | BASE64_ALPHABET.indexOf(char);\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((buffer >> bits) & 0xff);\n }\n }\n return Uint8Array.from(bytes);\n}\n\nfunction decodeHex(input: string): Uint8Array {\n const bytes = new Uint8Array(input.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = parseInt(input.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Normalizes a secp256k1 private key to a fresh 32-byte array (the caller may zero it). Also\n * accepts 32 raw bytes, which are validated and copied. For strings it accepts what `@gala-chain/api`'s\n * `normalizePrivateKey` accepted for a usable key: 64 hex characters (optionally `0x`-prefixed;\n * a 63-character hex key is left-padded with a zero) or a 44-character base64 string.\n *\n * @throws GalaSDKError (`INVALID_PRIVATE_KEY`; `params.reason` is one of\n * `INVALID_PRIVATE_KEY_REASONS`: `wrong_length` for raw bytes that are not 32 long,\n * `bad_encoding` for any other string shape, `not_on_curve` for an out-of-range scalar).\n */\nexport function normalizePrivateKey(input: string | Uint8Array): Uint8Array {\n if (typeof input !== 'string') {\n // Raw bytes: validated, then COPIED, so zeroing the result never touches the caller's array.\n if (!(input instanceof Uint8Array) || input.length !== 32) {\n throw invalidPrivateKey('wrong_length');\n }\n if (!secp256k1.utils.isValidSecretKey(input)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return Uint8Array.from(input);\n }\n const withoutPrefix = input.startsWith('0x') ? input.slice(2) : input;\n let key: Uint8Array | undefined;\n if (/^[0-9a-fA-F]{63,64}$/u.test(withoutPrefix)) {\n key = decodeHex(withoutPrefix.length === 63 ? `0${withoutPrefix}` : withoutPrefix);\n } else if (withoutPrefix.length === 44) {\n key = decodeBase64(withoutPrefix);\n }\n if (key?.length !== 32) {\n throw invalidPrivateKey('bad_encoding');\n }\n if (!secp256k1.utils.isValidSecretKey(key)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return key;\n}\n\n/**\n * Signs a 32-byte keccak256 hash and returns GalaChain's recoverable signature: 64 hex `r` +\n * 64 hex `s` + `1b`/`1c` (`v`), lowercase, no `0x`. Deterministic (RFC 6979) and low-S, exactly\n * what `@gala-chain/api` and the Gala Wallet produce. A DER signature carries no recovery byte\n * and cannot be used: the chain RECOVERS the signer from the signature.\n */\nexport function signHash(privateKey: Uint8Array, hash: Uint8Array): string {\n if (hash.length !== 32) {\n throw new GalaSDKError('INVALID_SIGNING_HASH_LENGTH', { length: hash.length });\n }\n const signature = secp256k1.sign(hash, privateKey, { prehash: false, lowS: true });\n // compact raw bytes are r (32) || s (32); the recovery id becomes v.\n return bytesToHex(signature.toBytes('compact')) + (signature.recovery === 1 ? '1c' : '1b');\n}\n\n/**\n * The lowercase `0x` Ethereum address (last 20 bytes of keccak256 of the uncompressed public key)\n * of a normalized private key. The Gala `eth|` identity of a key is this address.\n */\nexport function ethAddressOfPrivateKey(privateKey: Uint8Array): string {\n const publicKey = secp256k1.getPublicKey(privateKey, false);\n return `0x${bytesToHex(keccak_256(publicKey.slice(1)).slice(-20))}`;\n}\n\n/** keccak256 of a string's UTF-8 bytes. */\nexport function keccak256Utf8(data: string): Uint8Array {\n return keccak_256(textEncoder.encode(data));\n}\n\n/**\n * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes, with no\n * prefix and no signature envelope. The caller owns serialization, so the bytes shown to a user\n * and the bytes signed can never diverge.\n */\nexport function signSerializedNative(privateKey: Uint8Array, serializedDto: string): string {\n return signHash(privateKey, keccak256Utf8(serializedDto));\n}\n\n/**\n * GalaChain NATIVE signature for a DTO: keccak256 of `getPayloadToSign(dto)`, signed with\n * secp256k1. Byte-identical to `signatures.getSignature` from `@gala-chain/api`.\n */\nexport function signNative(privateKey: Uint8Array, dto: Record<string, unknown>): string {\n return signSerializedNative(privateKey, getPayloadToSign(dto));\n}\n\n/**\n * Personal-sign hash and signature: keccak256(`prefix` + `message`), both hashed VERBATIM with no\n * further EIP-191 wrapping. Passing `prefix = calculatePersonalSignPrefix(message)` reproduces a\n * wallet's `personal_sign` of `message`. Gala Wallet's `gala_signChainDto` (personal-sign\n * scheme) hashes `prefix` + the exact string it is handed, which can differ from the bare message\n * (see the `signatureOverPrefixlessBody` vectors); that quirk is why the two inputs stay separate.\n */\nexport function signPersonalMessage(\n privateKey: Uint8Array,\n prefix: string,\n message: string,\n): string {\n return signHash(privateKey, keccak256Utf8(prefix + message));\n}\n","import { GalaSDKError, isGalaError } from './gala_sdk_error.js';\nimport { assertNoEthZeroXPrefix } from '../writes/identity.js';\nimport {\n buildEIP712Payload,\n EIP712_CAPABLE_METHODS,\n eip712DomainFor,\n type EIP712DomainValue,\n type EIP712Types,\n} from '../utils/eip712.js';\nimport {\n ethAddressOfPrivateKey,\n fixpointPrefixFor,\n normalizePrivateKey,\n personalSignPrefixFor,\n serialize,\n signNative,\n} from '../utils/signing.js';\n\n// Personal-sign prefix, computed the way THE CHAIN verifies it.\n//\n// GalaChain (SDK 3.x) recovers a personal-signed DTO from\n// keccak256(<prefix field> + <canonical JSON of the DTO WITHOUT the prefix field>)\n// and a browser wallet's `personal_sign` (EIP-191) hashes\n// \"\\u0019Ethereum Signed Message:\\n\" + <byte length of message> + <message>.\n// They agree exactly when the wallet signs the bare canonical DTO and `prefix` is the EIP-191\n// header for that message's UTF-8 BYTE length. Any other message still yields a valid-looking\n// signature — it just recovers to an address nobody holds. This SDK used to embed `prefix` in\n// the signed message (the SDK 1.10 client recipe): observed on stage 2026-09-23, such a\n// MetaMask-signed CreatePool executed on chain under a phantom creator, and the swap backend's\n// write guard now rejects that shape outright.\n//\n// `@gala-chain/connect`'s prefix helper must NOT be used for wallet `personal_sign`: its\n// fixpoint counts the prefix itself and targets the SDK's raw-payload signer. The same header\n// is also what Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepends before hashing,\n// so one value serves both paths.\n//\n// The header itself is computed by `personalSignPrefixFor` in ../utils/signing.ts.\n\n/** The signing schemes supported by the Gala Wallet signer. */\nexport type GalaWalletScheme = 'native' | 'personal-sign';\n\n/** The request surface used by an EIP-1193 browser wallet. */\nexport interface BrowserWalletProvider {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n}\n\n/** The Gala Wallet extension's API (`window.gala`, or the same object from an EIP-6963 announcement). */\nexport interface GalaWalletApi {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n /** Gala Wallet's \"act as this account\" switch; absent on other providers. */\n setAddress?: (address: string) => Promise<void>;\n}\n\ninterface WindowWithGala {\n gala?: GalaWalletApi;\n}\n\ninterface GlobalWithWindow {\n window?: WindowWithGala;\n}\n\n/** A DTO together with the signature that belongs in the gateway request body. */\nexport type SignedDto<T extends Record<string, unknown>> = T & { signature: string };\n\n/**\n * A signer for complete GalaChain write bodies.\n *\n * Implementations return the DTO fields together with the signature that belongs in the\n * gateway request body. Signer identity is recovered from that signature; implementations do\n * not add signer hints, typed-data metadata, or a domain.\n */\nexport interface GalaChainSigner {\n /**\n * Signs a DTO for a named GalaChain contract method.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n signObject<T extends Record<string, unknown>>(methodName: string, dto: T): Promise<SignedDto<T>>;\n}\n\nfunction getWalletProvider(): GalaWalletApi {\n const globalObject = globalThis as GlobalWithWindow;\n const wallet = globalObject.window?.gala;\n if (!wallet) {\n throw new GalaSDKError('GALA_WALLET_NOT_AVAILABLE', {});\n }\n return wallet;\n}\n\nfunction getNativeSignature(value: unknown): string {\n if (typeof value !== 'string') {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n // 130 hex digits (r || s || v), bare as Gala Wallet returns it or `0x`-prefixed; passed on\n // verbatim, because the backend recovers the signer from either spelling.\n if (!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n return value;\n}\n\nfunction getPersonalSignature(value: unknown): string {\n if (typeof value !== 'string' || !/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'personal-sign' });\n }\n return value;\n}\n\n/**\n * The `0x`-prefixed Ethereum address a Gala account is signed by, or `undefined` when the account\n * names no key (a `client|` alias or a bare GalaChain id is not derivable from a key). Accepts\n * `0x` plus 40 hex digits and `eth|` plus 40 hex digits; the caller's casing is kept. `eth|0x...`\n * is not an address form and is refused. For {@link LazyPrivateKeySignerOptions.expectedAddress}, which should only be set for\n * an account whose key can be checked.\n *\n * @example\n * ```ts\n * createLazyPrivateKeySigner(getKey, { expectedAddress: ethereumAddressOfAccount(account) });\n * ```\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` for `eth|0x...` (refused, never read as\n * \"names no key\", which would switch a signer's address check off).\n */\nexport function ethereumAddressOfAccount(account: string): string | undefined {\n assertNoEthZeroXPrefix(account, 'account');\n const match = /^(?:eth\\||0x)([0-9a-fA-F]{40})$/u.exec(account);\n return match?.[1] === undefined ? undefined : `0x${match[1]}`;\n}\n\nfunction normalizeEthereumAccount(\n address: string,\n allowGalaPrefix: boolean,\n field = 'walletAddress',\n): string {\n assertNoEthZeroXPrefix(address, field);\n const normalized = allowGalaPrefix ? (ethereumAddressOfAccount(address) ?? address) : address;\n if (!/^0x[0-9a-fA-F]{40}$/u.test(normalized)) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field, value: address });\n }\n // The caller's casing is kept on purpose: the Gala web apps and the wallet hand the wallet the\n // checksummed account, and EIP-1193 / Gala Wallet accept any case, so passing the value through\n // unchanged is the only choice that cannot differ from what they send.\n return normalized;\n}\n\n/**\n * The account handed to Gala Wallet as the signer address. An Ethereum account is held to the\n * same strict check as ever (`0x` plus 40 hex digits; `eth|` plus 40 hex digits is normalized to\n * it; `eth|0x...` is refused). A GalaChain id the wallet can also be asked to sign for is passed\n * through verbatim: `client|` plus 24 hex digits, or the bare 24 hex digits that a web app keeps\n * after a direct `client|` login. Nothing else is accepted.\n */\nfunction normalizeGalaWalletAccount(address: string): string {\n assertNoEthZeroXPrefix(address, 'walletAddress');\n const eth = /^eth\\|([0-9a-fA-F]{40})$/u.exec(address);\n if (eth?.[1] !== undefined) return `0x${eth[1]}`;\n if (/^0x[0-9a-fA-F]{40}$/u.test(address) || /^(?:client\\|)?[0-9a-fA-F]{24}$/u.test(address)) {\n return address;\n }\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field: 'walletAddress', value: address });\n}\n\n/** An identity Gala Wallet can act as: an account form above, any `eth|`/`client|` alias, verbatim. */\nfunction assertWalletIdentity(identity: string): void {\n assertNoEthZeroXPrefix(identity, 'selectAddress');\n if (\n !/^(?:eth\\|[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\\|)?[0-9a-fA-F]{24})$/u.test(identity)\n ) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field: 'selectAddress', value: identity });\n }\n}\n\n/** Provider-wide queue: `setAddress` + the signature request must not interleave across signers. */\nconst walletIdentityQueue = new WeakMap<object, Promise<unknown>>();\n\n/**\n * Runs `signWith` with `identity` selected on a Gala Wallet that supports `setAddress`. Gala\n * Wallet holds ONE current account, so two signatures for different identities in flight at once\n * would sign as whichever selection came last; the pair (select, sign) is therefore serialized\n * per wallet object, across every signer and provider that signs through it\n * (`GalaWalletSigner`, `./providers`' `GalaWalletProvider`). A failed selection fails the\n * signature (nothing is requested). Without an identity, or on a wallet without `setAddress`, it\n * just runs `signWith`.\n *\n * @example\n * ```typescript\n * const signature = await withGalaWalletIdentity(window.gala, 'eth|70997970C51812dc3A010C7d01b50e0d17dc79C8', () =>\n * window.gala.request({ method: 'personal_sign', params: [hexMessage, address] }),\n * );\n * ```\n */\nexport function withGalaWalletIdentity<T>(\n wallet: GalaWalletApi,\n identity: string | undefined,\n signWith: () => Promise<T>,\n): Promise<T> {\n const { setAddress } = wallet;\n if (identity === undefined || typeof setAddress !== 'function') return signWith();\n const previous = walletIdentityQueue.get(wallet) ?? Promise.resolve();\n const run = previous\n .catch(() => undefined)\n .then(async () => {\n await setAddress.call(wallet, identity);\n return signWith();\n });\n walletIdentityQueue.set(wallet, run);\n return run;\n}\n\nfunction personalSign<T extends Record<string, unknown>>(\n provider: GalaWalletApi | BrowserWalletProvider,\n dto: T,\n walletAddress: string,\n methodName?: string,\n): Promise<T & { prefix: string; signature: string }> {\n const prefix = personalSignPrefixFor(dto);\n const payload = { ...dto, prefix };\n // A browser wallet's `personal_sign` applies the EIP-191 header ITSELF, so it must sign the\n // bare DTO; Gala Wallet's `gala_signChainDto` (personal-sign scheme) instead extracts the\n // `prefix` field from what it is handed and prepends it before hashing, so it is handed the\n // prefixed payload. Both submit `{ ...dto, prefix, signature }`.\n const params =\n methodName !== undefined\n ? [serialize(payload), walletAddress, methodName]\n : [serialize(dto), walletAddress];\n\n return provider\n .request({ method: methodName !== undefined ? 'gala_signChainDto' : 'personal_sign', params })\n .then((value) => ({ ...payload, signature: getPersonalSignature(value) }));\n}\n\n/**\n * Signs a DTO via genuine EIP-712 (`eth_signTypedData_v4`) — correctly resolves the `client|`\n * identity, unlike `personal_sign`, for the operations in `EIP712_CAPABLE_METHODS`.\n *\n * Constructs the raw JSON-RPC payload by hand (`{domain, types: {...types, EIP712Domain},\n * primaryType, message}`) rather than depending on ethers.js, matching exactly what\n * `ethers.TypedDataEncoder.getPayload`/`Wallet.signTypedData` produce internally — verified\n * byte-for-byte equivalent (same recovered address from the same signature against both\n * constructions) before this shipped, since the core SDK deliberately has no ethers dependency.\n */\nasync function signEIP712<T extends Record<string, unknown>>(\n provider: BrowserWalletProvider,\n methodName: string,\n dto: T,\n walletAddress: string,\n domainName?: string,\n): Promise<T & { types: EIP712Types; domain: EIP712DomainValue; signature: string }> {\n const { completedDto, types } = buildEIP712Payload(methodName, dto);\n // The wallet's LIVE chain id, read on every signature: a user can switch networks after\n // connecting, and a cached or hardcoded id would sign a domain MetaMask itself rejects. The\n // name is the deployment's (`eip712DomainName`), `ethereum` when none is given.\n const domain = eip712DomainFor(\n await provider.request({ method: 'eth_chainId', params: [] }),\n domainName,\n );\n // The body `prefix` is not part of the EIP-712 `types`, so it is never hashed; it carries the\n // connect-style fixpoint value only to keep the submitted body byte-identical to what the Gala\n // web apps have always sent.\n const prefix = fixpointPrefixFor(completedDto);\n const message = { ...completedDto, prefix };\n const eip712Domain = [\n { name: 'name', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n ];\n const payload = {\n domain,\n types: { ...types, EIP712Domain: eip712Domain },\n primaryType: methodName,\n message,\n };\n\n const value = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [walletAddress, JSON.stringify(payload)],\n });\n // Key order matches the body the Gala web apps submit: ..., prefix, signature, types, domain.\n return {\n ...(message as T & { prefix: string }),\n signature: getPersonalSignature(value),\n types,\n domain,\n };\n}\n\n/**\n * A GalaChain native signer backed by a secp256k1 private key.\n *\n * Native signing produces the bare GalaChain signature format, without a personal-sign prefix\n * or EIP-712 metadata. The private-key identity is recovered by the chain.\n */\nexport class PrivateKeySigner implements GalaChainSigner {\n private readonly privateKey: Uint8Array;\n\n /**\n * Creates a native signer from a hex or base64 secp256k1 private key.\n *\n * @example\n * ```typescript\n * const signer = new PrivateKeySigner('1'.padStart(64, '0'));\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n constructor(privateKey: string) {\n this.privateKey = normalizePrivateKey(privateKey);\n }\n\n /**\n * Signs the DTO with GalaChain native signing.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const signature = signNative(this.privateKey, dto);\n return Promise.resolve({ ...dto, signature });\n }\n}\n\n/** Supplies a private key at sign time: a hex/base64 string, possibly fetched asynchronously. */\nexport type PrivateKeyProvider = () => Promise<string> | string;\n\n/** Options for {@link createLazyPrivateKeySigner}. */\nexport interface LazyPrivateKeySignerOptions {\n /**\n * When set, every signature first checks that the fetched key belongs to this account (`0x...`\n * or the Gala `eth|<40 hex>` form, case-insensitive; `eth|0x...` is refused at creation) and\n * refuses to sign otherwise (`SIGNER_ADDRESS_MISMATCH`). Use it when the key lives in a slot another surface can switch\n * between the moment a request was approved and the moment it is signed.\n */\n expectedAddress?: string | undefined;\n}\n\n/**\n * Calls the app's key provider. Whatever it throws or rejects with is the app's own failure to\n * produce a key before anything was signed or sent, so it becomes `KEY_PROVIDER_FAILED` (the\n * original is `cause`); an SDK error is already catalogued and passes through.\n */\nasync function keyFrom(getPrivateKey: PrivateKeyProvider): Promise<unknown> {\n try {\n return await getPrivateKey();\n } catch (cause: unknown) {\n throw isGalaError(cause) ? cause : new GalaSDKError('KEY_PROVIDER_FAILED', {}, { cause });\n }\n}\n\n/**\n * Creates the native-signing equivalent of {@link PrivateKeySigner} for apps that must not hold a\n * key in a long-lived object (an extension that reads its session key at sign time).\n *\n * `getPrivateKey` is called once per `signObject` call, never cached, never shared between calls\n * (concurrent signatures each fetch their own key), and the normalized key bytes are zeroed\n * before `signObject` settles, also on failure. A rejection or exception from `getPrivateKey` (the\n * app's \"wallet is locked\", a storage read that failed) is a `KEY_PROVIDER_FAILED` error with the\n * original error as `cause`: nothing has been sent, so `classifyFailure` says `not_sent` and Retry\n * is safe, and the app needs no error class of its own to tell this apart. A provider that returns\n * no usable string (`''`, `undefined`) is `INVALID_PRIVATE_KEY` with `reason: 'no_key_provided'`,\n * classified the same way; any other key that is not a valid secp256k1 key string is an\n * `INVALID_PRIVATE_KEY` error. An SDK error the provider throws itself is passed through.\n * Signatures are byte-identical to `new PrivateKeySigner(key).signObject(...)`.\n *\n * A JavaScript string cannot be wiped; the provider owns the lifetime of the string it returns.\n *\n * @example\n * ```typescript\n * const signer = createLazyPrivateKeySigner(\n * () => SecurityHelper.getSessionSecret(SecurityHelper.SESSION_PRIVATE_KEY_KEY),\n * { expectedAddress: account.address },\n * );\n * const gswap = new GSwap({ signer });\n * ```\n */\nexport function createLazyPrivateKeySigner(\n getPrivateKey: PrivateKeyProvider,\n options: LazyPrivateKeySignerOptions = {},\n): GalaChainSigner {\n const expected = options.expectedAddress;\n const expectedLower =\n expected === undefined\n ? undefined\n : normalizeEthereumAccount(expected, true, 'expectedAddress').toLowerCase();\n\n return {\n async signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const provided: unknown = await keyFrom(getPrivateKey);\n if (typeof provided !== 'string' || provided === '') {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'no_key_provided' });\n }\n const key = normalizePrivateKey(provided);\n try {\n if (expectedLower !== undefined && ethAddressOfPrivateKey(key) !== expectedLower) {\n throw new GalaSDKError('SIGNER_ADDRESS_MISMATCH', {});\n }\n return { ...dto, signature: signNative(key, dto) };\n } finally {\n key.fill(0);\n }\n },\n };\n}\n\n/**\n * A Gala Wallet signer using native GalaChain signing, with an opt-in personal-sign mode.\n *\n * The selected Ethereum account is passed to Gala Wallet. There is NO automatic fallback: a\n * wallet that rejects `native` surfaces its error to the caller, because the only alternative,\n * `personal-sign`, silently recovers a phantom signer on every released Gala Wallet.\n *\n * `scheme: 'personal-sign'` calls\n * `gala_signChainDto([serialize({ ...dto, prefix }), walletAddress, methodName])` and REQUIRES\n * a Gala Wallet build that strips the embedded `prefix` field and hashes `prefix` + the\n * prefix-less canonical body (the chain's scheme). Wallet builds that predate that fix hash the\n * string with the `prefix` field still inside it and the signature recovers to an address\n * nobody holds, so only opt in once the wallet you target has the fix.\n */\nexport class GalaWalletSigner implements GalaChainSigner {\n /** The wallet address supplied to Gala Wallet for each signing request. */\n public readonly walletAddress: string;\n\n /** The signing scheme used for every request; it never changes after construction. */\n public readonly scheme: GalaWalletScheme;\n\n /**\n * Creates a Gala Wallet signer.\n *\n * @example\n * ```typescript\n * const signer = new GalaWalletSigner('0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n *\n * @param walletAddress - The account passed to Gala Wallet as the signer address. An Ethereum\n * account is `0x` plus 40 hex digits (Gala Wallet's `eth|...` form is normalized to it and held\n * to the same check); a GalaChain id is `client|` plus 24 hex digits, or the bare 24 hex digits\n * a web app keeps for a direct `client|` login, and is passed through unchanged.\n * @param options - Select native signing (default) or personal-sign explicitly.\n * `'personal-sign'` requires a Gala Wallet build that signs the bare serialized DTO.\n * `selectAddress` is the identity (`client|...` / `eth|...`) Gala Wallet is switched to with\n * `setAddress` before every signature, when the wallet offers it. `wallet` is the Gala Wallet\n * object to sign through (the one an EIP-6963 announcement or a wallet provider holds); without\n * it, `window.gala` is read at every signature.\n */\n constructor(\n walletAddress: string,\n options: {\n scheme?: GalaWalletScheme | undefined;\n selectAddress?: string | undefined;\n wallet?: GalaWalletApi | undefined;\n } = {},\n ) {\n this.walletAddress = normalizeGalaWalletAccount(walletAddress);\n this.scheme = options.scheme ?? 'native';\n if (options.selectAddress !== undefined) assertWalletIdentity(options.selectAddress);\n this.selectAddress = options.selectAddress;\n this.wallet = options.wallet;\n }\n\n /** The identity Gala Wallet is switched to before each signature, if one was given. */\n public readonly selectAddress: string | undefined;\n\n /** The Gala Wallet object this signer signs through; `undefined` reads `window.gala` each time. */\n private readonly wallet: GalaWalletApi | undefined;\n\n /**\n * Signs a DTO through `gala_signChainDto`.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('AddLiquidity', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * tickLower: -60,\n * tickUpper: 60,\n * });\n * ```\n */\n public async signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const wallet = this.wallet ?? getWalletProvider();\n\n return withGalaWalletIdentity(wallet, this.selectAddress, async () => {\n if (this.scheme === 'personal-sign') {\n return personalSign(wallet, dto, this.walletAddress, methodName);\n }\n const signature = await wallet.request({\n method: 'gala_signChainDto',\n params: [serialize(dto), this.walletAddress, methodName, 'native'],\n });\n return { ...dto, signature: getNativeSignature(signature) };\n });\n }\n}\n\n/**\n * A personal-sign signer for MetaMask and other EIP-1193 browser wallets.\n *\n * The chain recovers this signature using the EIP-191 wrap applied by the wallet to\n * `personal_sign`. This is the browser-wallet path used by the v2 frontend and resolves the\n * bare `eth|` identity.\n */\nexport class BrowserWalletSigner implements GalaChainSigner {\n /**\n * Creates a browser-wallet signer.\n *\n * Defaults to `personal_sign` — unchanged from every existing integration, since it only ever\n * resolves the bare `eth|` identity and changing that silently would be a real behavior\n * break for anyone already depending on it. Pass `{ scheme: 'eip712' }` to correctly resolve\n * a registered `client|` alias instead, for `RequestTrade`/`AddLiquidity`/`RemoveLiquidity`/\n * `CollectPositionFees` (`EIP712_CAPABLE_METHODS`) — `CreatePool` and any other method still\n * falls back to `personal_sign` even in `'eip712'` mode, since its EIP-712 signing is a\n * separate, unsolved chain-side problem.\n *\n * `eip712DomainName` is the EIP-712 domain name every typed-data signature carries (the\n * `'eip712'` scheme only; `personal_sign` has no domain): the deployment's own\n * (`GALA_CHAIN_ENVIRONMENTS[env].eip712DomainName`), `ethereum` when absent.\n *\n * @example\n * ```typescript\n * const signer = new BrowserWalletSigner(window.ethereum, '0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n * @example\n * ```typescript\n * // Correctly resolves a registered client| alias instead of the bare eth| address.\n * const signer = new BrowserWalletSigner(window.ethereum, walletAddress, { scheme: 'eip712' });\n * ```\n * @example\n * ```typescript\n * // The stage chain refuses any EIP-712 domain name but its own.\n * const signer = new BrowserWalletSigner(window.ethereum, walletAddress, {\n * scheme: 'eip712',\n * eip712DomainName: GALA_CHAIN_ENVIRONMENTS.stage.eip712DomainName,\n * });\n * ```\n */\n constructor(\n private readonly provider: BrowserWalletProvider,\n walletAddress: string,\n options: { scheme?: 'personal-sign' | 'eip712'; eip712DomainName?: string | undefined } = {},\n ) {\n this.walletAddress = normalizeEthereumAccount(walletAddress, false);\n this.scheme = options.scheme ?? 'personal-sign';\n this.eip712DomainName = options.eip712DomainName;\n }\n\n /** The selected `0x` Ethereum account every signature is requested for. */\n public readonly walletAddress: string;\n private readonly scheme: 'personal-sign' | 'eip712';\n private readonly eip712DomainName: string | undefined;\n\n /**\n * Signs the DTO with `eth_signTypedData_v4` (when constructed with `{ scheme: 'eip712' }` and\n * `methodName` is in `EIP712_CAPABLE_METHODS`) or the EIP-1193 `personal_sign` method\n * (otherwise — the default).\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n if (this.scheme === 'eip712' && EIP712_CAPABLE_METHODS.has(methodName)) {\n return signEIP712(this.provider, methodName, dto, this.walletAddress, this.eip712DomainName);\n }\n return personalSign(this.provider, dto, this.walletAddress);\n }\n}\n","/**\n * String-key signing entry points for apps that hold a private key only briefly (the Gala Wallet\n * extension reads its session key at sign time and must not keep it in a long-lived object).\n *\n * These are thin, byte-exact ports of the functions the wallet shipped (including the\n * fail-closed personal-sign payload resolver), re-expressed over the SDK's own primitives. Every\n * function takes the key as a string (`0x`-optional hex, or base64) or as bytes, normalizes it per\n * call, and zeroes the normalized copy before returning, so nothing in this module retains a key.\n * A JavaScript string cannot be wiped; the caller owns the lifetime of the string it passes in.\n */\nimport BigNumber from 'bignumber.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport {\n normalizePrivateKey,\n serialize,\n signPersonalMessage,\n signSerializedNative,\n} from './signing.js';\n\n/** A secp256k1 private key as a hex/base64 string or as raw 32 bytes. */\nexport type PrivateKeyInput = string | Uint8Array;\n\n/**\n * Runs `action` with a private normalized copy of the key, zeroed afterwards (also when `action`\n * throws). Bytes given by the caller are copied, never modified: the caller owns them.\n */\nexport function withPrivateKey<T>(privateKey: PrivateKeyInput, action: (key: Uint8Array) => T): T {\n const key = normalizePrivateKey(privateKey);\n try {\n return action(key);\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes with no\n * prefix and no envelope (wallet `signChainDtoNative`). The caller owns serialization, so the\n * bytes a user reviewed and the bytes signed cannot diverge.\n *\n * @returns 130 lowercase hex characters, `r || s || v` with `v` = `1b`/`1c`, no `0x`.\n */\nexport function signChainDtoNative(privateKey: PrivateKeyInput, serializedDto: string): string {\n return withPrivateKey(privateKey, (key) => signSerializedNative(key, serializedDto));\n}\n\n/**\n * The personal-sign hash primitive (wallet `signChainDtoHash`): keccak256(`prefix` + `message`),\n * both verbatim, with no further EIP-191 wrap. `message` must be the DTO's serialization WITHOUT\n * its `prefix` field; callers holding a dApp-supplied string go through `signChainDtoPersonalSign`,\n * which derives both inputs from it.\n */\nexport function signChainDtoHash(\n privateKey: PrivateKeyInput,\n prefix: string,\n message: string,\n): string {\n return withPrivateKey(privateKey, (key) => signPersonalMessage(key, prefix, message));\n}\n\nconst PERSONAL_SIGN_HEADER = String.fromCharCode(0x19) + 'Ethereum Signed Message:\\n';\nconst PERSONAL_SIGN_LENGTH_PATTERN = /^(?:0|[1-9][0-9]*)$/u;\n\n// A header with a body starting `{` can never collide with another EIP-191 message's hash, and\n// anything that is not a header (arbitrary bytes the user cannot see on an approval card) is\n// refused. The number is NOT required to equal the byte length: the chain hashes whatever prefix\n// the submitted DTO carries, and the swap backend's write guard rejects a mismatched header loudly.\nfunction isPersonalSignHeader(prefix: string): boolean {\n return (\n prefix.startsWith(PERSONAL_SIGN_HEADER) &&\n PERSONAL_SIGN_LENGTH_PATTERN.test(prefix.slice(PERSONAL_SIGN_HEADER.length))\n );\n}\n\n/**\n * Top-level fields that would make the chain (`getPayloadToSign`) or the swap backend's personal-sign\n * verifier hash something other than `prefix + serialize(dto minus prefix)`. An unsigned DTO from\n * a dApp never legitimately carries any of them, so they fail closed. Order is part of the error\n * message the wallet shows its user.\n */\nconst PERSONAL_SIGN_FORBIDDEN_FIELDS = [\n 'signature',\n 'multisig',\n 'trace',\n 'types',\n 'domain',\n 'stringsInstructions',\n] as const;\n\n/** What a `gala_signChainDto` personal-sign request hashes. */\nexport interface PersonalSignChainDtoPayload {\n /** The `prefix` the chain prepends: the DTO's own `prefix` field, or `''` when it has none. */\n prefix: string;\n /** The exact message hashed after `prefix`. */\n message: string;\n}\n\n/**\n * Derives what to hash for a `gala_signChainDto` personal-sign request from the exact string the\n * dApp sent (and the approval card displayed): wallet `resolvePersonalSignChainDtoPayload`.\n *\n * The dApp submits `{ ...dto, prefix, signature }`, which the chain recovers from\n * `keccak256(prefix + serialize(dto WITHOUT prefix))`. So when the string embeds a `prefix`\n * field, that field is removed and the remainder re-serialized; the prefix used is the dApp's own\n * value byte for byte. A string with no `prefix` field is hashed verbatim with an empty prefix\n * (chain-equivalent to a native signature of that exact string).\n *\n * Fails closed (throws `GalaSDKError` `PERSONAL_SIGN_NOT_JSON`, `PERSONAL_SIGN_NOT_OBJECT`,\n * `PERSONAL_SIGN_BAD_PREFIX`, `PERSONAL_SIGN_ENVELOPE_FIELDS` or `PERSONAL_SIGN_NOT_CANONICAL`) on:\n * malformed JSON; JSON that is not a plain object; a `prefix` that is not an EIP-191\n * \"Ethereum Signed Message\" header; any signing-envelope field (`signature`, `multisig`, `trace`,\n * `types`, `domain`, `stringsInstructions`); and a string that is not already the canonical\n * serialization of what it parses to (duplicate keys, lossy numbers, key-order tricks the card\n * would render differently). Stripping `prefix` is therefore the ONLY byte change between the\n * reviewed string and the signed message.\n */\nexport function resolvePersonalSignChainDtoPayload(data: string): PersonalSignChainDtoPayload {\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n throw new GalaSDKError('PERSONAL_SIGN_NOT_JSON', {});\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new GalaSDKError('PERSONAL_SIGN_NOT_OBJECT', {});\n }\n const dto = parsed as Record<string, unknown>;\n if (!Object.prototype.hasOwnProperty.call(dto, 'prefix')) {\n return { prefix: '', message: data };\n }\n\n const { prefix, ...withoutPrefix } = dto;\n if (typeof prefix !== 'string' || !isPersonalSignHeader(prefix)) {\n throw new GalaSDKError('PERSONAL_SIGN_BAD_PREFIX', {});\n }\n const forbidden = PERSONAL_SIGN_FORBIDDEN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(withoutPrefix, field),\n );\n if (forbidden.length > 0) {\n throw new GalaSDKError('PERSONAL_SIGN_ENVELOPE_FIELDS', { fields: forbidden.join(', ') });\n }\n if (serialize(dto) !== data) {\n throw new GalaSDKError('PERSONAL_SIGN_NOT_CANONICAL', {});\n }\n return { prefix, message: serialize(withoutPrefix) };\n}\n\n/**\n * Signs a GalaChain personal-sign scheme DTO from the exact string a dApp sent through\n * `gala_signChainDto` (wallet `signChainDtoPersonalSign`). See\n * `resolvePersonalSignChainDtoPayload` for what is signed and what is refused; the signature\n * recovers, under the chain's `getPayloadToSign`, to this key for the DTO the dApp submits with\n * its `prefix`, and equals a `personal_sign` of the bare body when that prefix is the EIP-191\n * header of the bare body's byte length.\n *\n * @throws GalaSDKError (`PERSONAL_SIGN_*`, see `resolvePersonalSignChainDtoPayload`) before any\n * signing when the input is refused.\n */\nexport function signChainDtoPersonalSign(privateKey: PrivateKeyInput, data: string): string {\n const { prefix, message } = resolvePersonalSignChainDtoPayload(data);\n return signChainDtoHash(privateKey, prefix, message);\n}\n\n/**\n * Raw object signing (wallet `signObject`), used for transfers, bridge and fee-dry-run DTOs the\n * wallet signs itself. Removes ONLY `signature`, signs `keccak256(serialize(rest))` natively\n * (no `prefix` handling, and `trace` / `multisig` stay in the signed bytes, unlike\n * `signNative`), and returns `{ signature, ...rest }` with the signature as the FIRST key, exactly\n * like the wallet. Callers that must not sign extra fields strip them first.\n */\nexport function signRawObject(\n privateKey: PrivateKeyInput,\n obj: Record<string, unknown>,\n): { signature: string } & Record<string, unknown> {\n const rest = { ...obj };\n delete rest['signature'];\n return {\n signature: signChainDtoNative(privateKey, serialize(rest)),\n ...rest,\n };\n}\n\n/**\n * Drops the `EIP712Domain` entry from a dApp-supplied types map (a typed-data encoder derives the\n * domain type itself and rejects an explicit one). The order of the remaining types is preserved.\n */\nexport function stripEip712DomainType<T>(types: Record<string, T>): Record<string, T> {\n const stripped: Record<string, T> = {};\n for (const typeName of Object.keys(types)) {\n if (typeName !== 'EIP712Domain') stripped[typeName] = types[typeName] as T;\n }\n return stripped;\n}\n\n/**\n * `collection$category$type$additionalKey` for a token-class object (wallet `decodeTokenData`).\n * Lenient on purpose: any missing or non-string part becomes `''`, so a display layer never\n * throws on odd input.\n */\nexport function tokenClassDollarKey(token: Record<string, unknown> | null | undefined): string {\n const part = (field: string): string => {\n const value = token?.[field];\n return typeof value === 'string' ? value : '';\n };\n return `${part('collection')}$${part('category')}$${part('type')}$${part('additionalKey')}`;\n}\n\n/**\n * A quantity in the form GalaChain's `IsBigNumber` validator accepts: FIXED notation, no leading\n * zeros, no trailing decimal zeros (`BigNumber#toFixed()`; never `toString()`, which turns\n * `0.00000001` into `1e-8`, and never a JS number in between).\n *\n * @throws GalaSDKError (`INVALID_DECIMAL`) for a value that is not a finite number. The wallet's\n * `cleanNumber` returned the string `'NaN'` there; signing that text can only fail on chain.\n */\nexport function canonicalDecimalString(value: string | number): string {\n let parsed = new BigNumber(Number.NaN);\n try {\n parsed = new BigNumber(value);\n } catch {\n // BigNumber throws instead of returning NaN when its DEBUG flag is on; both mean \"invalid\".\n }\n if (!parsed.isFinite()) {\n throw new GalaSDKError('INVALID_DECIMAL', { value: String(value) });\n }\n return parsed.toFixed();\n}\n","/**\n * EIP-712 (`eth_signTypedData_v4`) hashing and signing for ARBITRARY dApp typed data, built on the\n * SDK's own primitives (`@noble/curves`, `@noble/hashes`) so a wallet can sign a dApp's typed-data\n * approval without ethers. It replaces the wallet's `new ethers.Wallet(key).signTypedData(...)`\n * and is pinned to it: the golden suite reproduces every fixture signature exactly and a seeded\n * differential fuzz compares the digest and signature with ethers for every supported type.\n *\n * Compared with ethers this encoder is deliberately STRICTER (it fails closed rather than coerce):\n * `bool` accepts only a boolean, numbers accept only safe integers / decimal or `0x` strings,\n * strings must be well-formed UTF-16, struct values must be objects whose fields are their own\n * properties, and every struct, field and type name must be a plain identifier. Anything ethers\n * accepts that is NOT in that set is refused here instead of being signed in a different shape\n * from what a user reviewed.\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { hasValidEip55Casing } from './eth_address.js';\nimport { signHash } from './signing.js';\nimport { withPrivateKey, type PrivateKeyInput } from './chain_dto_signing.js';\n\n/** A typed-data payload as `eth_signTypedData_v4` carries it, minus `primaryType` (it is inferred). */\nexport interface TypedDataPayload {\n domain: Record<string, unknown>;\n /** Struct definitions WITHOUT `EIP712Domain` (see `stripEip712DomainType`). */\n types: Record<string, readonly unknown[]>;\n message: Record<string, unknown>;\n}\n\ninterface TypedField {\n name: string;\n type: string;\n}\n\nconst textEncoder = new TextEncoder();\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;\nconst TYPE_SYNTAX = /^([A-Za-z_$][A-Za-z0-9_$]*)((?:\\[(?:0|[1-9][0-9]*)?\\])*)$/u;\nconst BIGINT_DECIMAL = /^-?[0-9]+$/u;\nconst BIGINT_HEX = /^-?0x[0-9a-fA-F]+$/u;\n\n/** The EIP-712 domain members and their types, in the order ethers (and the spec) hash them. */\nconst DOMAIN_FIELDS: readonly TypedField[] = [\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n];\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction bigintToWord(value: bigint): Uint8Array {\n const word = new Uint8Array(32);\n // Every caller has bounds-checked `value` against its Solidity type, so it fits in 256 bits.\n let rest = value < 0n ? value + (1n << 256n) : value;\n for (let index = 31; index >= 0; index -= 1) {\n word[index] = Number(rest & 0xffn);\n rest >>= 8n;\n }\n return word;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const body = hex.slice(2);\n const out = new Uint8Array(body.length / 2);\n for (let index = 0; index < out.length; index += 1) {\n out[index] = parseInt(body.slice(index * 2, index * 2 + 2), 16);\n }\n return out;\n}\n\nfunction toBytes(value: unknown, what: string): Uint8Array {\n if (value instanceof Uint8Array) return value;\n if (typeof value === 'string' && /^0x(?:[0-9a-fA-F]{2})*$/u.test(value)) return hexToBytes(value);\n throw new GalaSDKError('TYPED_DATA_NOT_HEX_BYTES', { what });\n}\n\nfunction toBigInt(value: unknown, what: string): bigint {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value))\n throw new GalaSDKError('TYPED_DATA_NOT_SAFE_INTEGER', { what });\n return BigInt(value);\n }\n if (typeof value === 'string') {\n if (BIGINT_DECIMAL.test(value)) return BigInt(value);\n if (BIGINT_HEX.test(value)) {\n return value.startsWith('-') ? -BigInt(value.slice(1)) : BigInt(value);\n }\n }\n throw new GalaSDKError('TYPED_DATA_NOT_INTEGER', { what });\n}\n\nfunction utf8(value: unknown, what: string): Uint8Array {\n if (typeof value !== 'string') throw new GalaSDKError('TYPED_DATA_NOT_STRING', { what });\n for (let index = 0; index < value.length; index += 1) {\n const unit = value.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n }\n return textEncoder.encode(value);\n}\n\n/** EIP-55: a mixed-case address must carry the right checksum; all-lower / all-upper is accepted. */\nfunction addressBytes(value: unknown): Uint8Array {\n if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{40}$/u.test(value)) {\n throw new GalaSDKError('TYPED_DATA_BAD_ADDRESS', {});\n }\n if (!hasValidEip55Casing(value.slice(2))) {\n throw new GalaSDKError('TYPED_DATA_BAD_CHECKSUM', {});\n }\n return hexToBytes(value);\n}\n\ntype LeafEncoder = (value: unknown) => Uint8Array;\n\n/** The encoder for a non-struct, non-array type, or undefined when `base` is not one. */\nfunction leafEncoder(base: string): LeafEncoder | undefined {\n if (base === 'string') return (value) => keccak_256(utf8(value, 'string'));\n if (base === 'bytes') return (value) => keccak_256(toBytes(value, 'bytes'));\n if (base === 'bool') {\n return (value) => {\n if (typeof value !== 'boolean') throw new GalaSDKError('TYPED_DATA_NOT_BOOLEAN', {});\n return bigintToWord(value ? 1n : 0n);\n };\n }\n if (base === 'address') {\n return (value) => concat([new Uint8Array(12), addressBytes(value)]);\n }\n const fixed = /^bytes([1-9][0-9]?)$/u.exec(base);\n if (fixed !== null) {\n const width = Number(fixed[1]);\n // The pattern above admits no leading zero, so `String(width)` is always the digits written.\n if (width > 32) return undefined;\n return (value) => {\n const bytes = toBytes(value, base);\n if (bytes.length !== width) {\n throw new GalaSDKError('TYPED_DATA_BYTES_LENGTH', { type: base, width });\n }\n return concat([bytes, new Uint8Array(32 - width)]);\n };\n }\n const integer = /^(u?)int([1-9][0-9]*)$/u.exec(base);\n if (integer !== null) {\n const width = Number(integer[2]);\n if (width % 8 !== 0 || width > 256 || String(width) !== integer[2]) return undefined;\n const signed = integer[1] === '';\n const lower = signed ? -(1n << BigInt(width - 1)) : 0n;\n const upper = signed ? (1n << BigInt(width - 1)) - 1n : (1n << BigInt(width)) - 1n;\n return (value) => {\n const number = toBigInt(value, base);\n if (number < lower || number > upper) {\n throw new GalaSDKError('TYPED_DATA_OUT_OF_BOUNDS', { type: base });\n }\n return bigintToWord(number);\n };\n }\n return undefined;\n}\n\ninterface ParsedType {\n base: string;\n /** Array suffixes outermost-last, e.g. `uint256[2][]` is `[2, -1]` (-1 = dynamic). */\n dimensions: number[];\n}\n\nfunction parseType(type: string): ParsedType {\n const match = TYPE_SYNTAX.exec(type);\n if (match === null) throw new GalaSDKError('TYPED_DATA_UNSUPPORTED_TYPE', { type });\n // Group 2 of TYPE_SYNTAX is `(...)*` around the whole suffix run, so it always participates.\n const dimensions = [...(match[2] as string).matchAll(/\\[([0-9]*)\\]/gu)].map((dimension) =>\n dimension[1] === '' ? -1 : Number(dimension[1]),\n );\n return { base: match[1] as string, dimensions };\n}\n\nfunction parseFields(typeName: string, rawFields: readonly unknown[]): TypedField[] {\n if (!Array.isArray(rawFields)) throw new GalaSDKError('TYPED_DATA_FIELDS_NOT_LIST', { typeName });\n const seen = new Set<string>();\n return rawFields.map((raw: unknown) => {\n const field = raw as { name?: unknown; type?: unknown } | null;\n if (typeof field?.name !== 'string' || typeof field.type !== 'string') {\n throw new GalaSDKError('TYPED_DATA_FIELD_MALFORMED', { typeName });\n }\n if (!IDENTIFIER.test(field.name)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_FIELD_NAME', { name: field.name });\n }\n if (seen.has(field.name)) {\n throw new GalaSDKError('TYPED_DATA_DUPLICATE_FIELD', { name: field.name, typeName });\n }\n seen.add(field.name);\n // A bare `int` / `uint` is the 256-bit type and is hashed as `int256` / `uint256`, like ethers.\n const parsed = parseType(field.type);\n const base =\n parsed.base === 'uint' || parsed.base === 'int' ? `${parsed.base}256` : parsed.base;\n return { name: field.name, type: base + field.type.slice(parsed.base.length) };\n });\n}\n\ninterface StructEncoder {\n primaryType: string;\n hashStruct: (typeName: string, value: unknown) => Uint8Array;\n}\n\n/**\n * Builds the struct encoder for a set of type definitions: validates the type graph (unknown or\n * circular references, duplicate fields) and infers the primary type as the single type no other\n * type references, exactly like ethers' `TypedDataEncoder`.\n */\nfunction createStructEncoder(rawTypes: Record<string, readonly unknown[]>): StructEncoder {\n const names = Object.keys(rawTypes);\n const fields = new Map<string, TypedField[]>();\n for (const name of names) {\n if (!IDENTIFIER.test(name)) throw new GalaSDKError('TYPED_DATA_INVALID_TYPE_NAME', { name });\n fields.set(name, parseFields(name, rawTypes[name] as readonly unknown[]));\n }\n\n const children = new Map<string, Set<string>>();\n const parents = new Map<string, Set<string>>();\n for (const name of names) {\n children.set(name, new Set());\n parents.set(name, new Set());\n }\n for (const [name, list] of fields) {\n for (const field of list) {\n const { base } = parseType(field.type);\n if (base === name) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (leafEncoder(base) !== undefined) continue;\n if (!fields.has(base)) {\n throw new GalaSDKError('TYPED_DATA_UNKNOWN_FIELD_TYPE', { type: base, typeName: name });\n }\n children.get(name)?.add(base);\n parents.get(base)?.add(name);\n }\n }\n\n const roots = names.filter((name) => parents.get(name)?.size === 0);\n if (roots.length === 0) throw new GalaSDKError('TYPED_DATA_NO_PRIMARY_TYPE', {});\n if (roots.length > 1) {\n throw new GalaSDKError('TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE', { roots: roots.join(', ') });\n }\n const primaryType = roots[0] as string;\n\n const visiting = new Set<string>();\n const checked = new Set<string>();\n const checkCircular = (name: string): void => {\n if (visiting.has(name)) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (checked.has(name)) return;\n visiting.add(name);\n // `children` holds an entry for every name, and `name` is always one of them.\n for (const child of children.get(name) as Set<string>) checkCircular(child);\n visiting.delete(name);\n checked.add(name);\n };\n checkCircular(primaryType);\n\n const dependencies = (name: string, found: Set<string>): Set<string> => {\n for (const child of children.get(name) as Set<string>) {\n if (!found.has(child)) {\n found.add(child);\n dependencies(child, found);\n }\n }\n return found;\n };\n const encodeOne = (name: string): string =>\n `${name}(${(fields.get(name) as TypedField[]).map((field) => `${field.type} ${field.name}`).join(',')})`;\n const typeHashes = new Map<string, Uint8Array>();\n for (const name of names) {\n const sorted = [...dependencies(name, new Set())].filter((dep) => dep !== name).sort();\n typeHashes.set(name, keccak_256(textEncoder.encode([name, ...sorted].map(encodeOne).join(''))));\n }\n\n const encodeValue = (parsed: ParsedType, value: unknown, depth: number): Uint8Array => {\n // The LAST bracket written is the outermost array: `uint8[][2]` is two `uint8[]`.\n const dimension = parsed.dimensions[parsed.dimensions.length - 1 - depth];\n if (dimension !== undefined) {\n if (!Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_EXPECTED', { type: parsed.base });\n }\n if (dimension !== -1 && dimension !== value.length) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_LENGTH_MISMATCH', {});\n }\n return keccak_256(concat(value.map((item) => encodeValue(parsed, item, depth + 1))));\n }\n const leaf = leafEncoder(parsed.base);\n if (leaf !== undefined) return leaf(value);\n return hashStruct(parsed.base, value);\n };\n\n function hashStruct(typeName: string, value: unknown): Uint8Array {\n // createStructEncoder has already validated every struct name this is called with (the\n // primary type, the domain type, and each field base that is not a leaf type).\n const list = fields.get(typeName) as TypedField[];\n const typeHash = typeHashes.get(typeName) as Uint8Array;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_STRUCT_NOT_OBJECT', { typeName });\n }\n const record = value as Record<string, unknown>;\n const words = list.map((field) => {\n if (!Object.prototype.hasOwnProperty.call(record, field.name)) {\n throw new GalaSDKError('TYPED_DATA_MISSING_FIELD', { typeName, field: field.name });\n }\n // Struct-valued fields are encoded to their 32-byte struct hash by encodeValue.\n return encodeValue(parseType(field.type), record[field.name], 0);\n });\n return keccak_256(concat([typeHash, ...words]));\n }\n\n return { primaryType, hashStruct };\n}\n\nfunction hashDomain(domain: Record<string, unknown>): Uint8Array {\n if (domain === null || typeof domain !== 'object' || Array.isArray(domain)) {\n throw new GalaSDKError('TYPED_DATA_DOMAIN_NOT_OBJECT', {});\n }\n for (const key of Object.keys(domain)) {\n if (!DOMAIN_FIELDS.some((field) => field.name === key)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_DOMAIN_KEY', { key: JSON.stringify(key) });\n }\n }\n const present = DOMAIN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(domain, field.name),\n );\n const encoder = createStructEncoder({ EIP712Domain: present });\n return encoder.hashStruct('EIP712Domain', domain);\n}\n\n/**\n * The EIP-712 digest `keccak256(0x1901 || domainSeparator || hashStruct(primaryType, message))`\n * that a wallet signs for `eth_signTypedData_v4`. The primary type is inferred, as ethers does.\n *\n * @throws GalaSDKError (`TYPED_DATA_*`) for any type graph or value it cannot encode\n * exactly (see the module note on strictness).\n */\nexport function hashTypedData(payload: TypedDataPayload): Uint8Array {\n const domainHash = hashDomain(payload.domain);\n const encoder = createStructEncoder(payload.types);\n const structHash = encoder.hashStruct(encoder.primaryType, payload.message);\n return keccak_256(concat([Uint8Array.of(0x19, 0x01), domainHash, structHash]));\n}\n\n/**\n * Signs a dApp's EIP-712 typed-data approval (the wallet's `signTypedMessage` path), replacing\n * `new ethers.Wallet(key).signTypedData(domain, types, message)`. `types` must already have\n * `EIP712Domain` removed (`stripEip712DomainType`).\n *\n * @returns `0x` + r + s + v with `v` = `0x1b`/`0x1c` (27/28): ethers' serialized signature form,\n * recoverable with `verifyTypedData` / `eth_signTypedData_v4` verifiers. Rejects (never throws\n * synchronously) on invalid input.\n */\nexport async function signTypedDataPayload(\n privateKey: PrivateKeyInput,\n payload: TypedDataPayload,\n): Promise<string> {\n const digest = hashTypedData(payload);\n return withPrivateKey(privateKey, (key) => `0x${signHash(key, digest)}`);\n}\n","/**\n * The chain's operation ids for the GalaChain contracts the gateway routes, from the gateway's\n * `dtoOperationMap` (the `dtoOperation` / API path table of the GalaChain platform team,\n * 2026-10-27). The chain refuses a signed DTO whose `dtoOperation` is not exactly the operation it\n * is called through (\"The dto was signed to call X operation, but the current operation is Y\"), so\n * the URL a write is POSTed to and the `dtoOperation` it carries both come from this one table and\n * can never disagree.\n *\n * `dtoOperation` is a SIGNED field: it is part of the DTO before the signer sees it, never added by\n * a signer or after the signature.\n */\n\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\n\n/** `<channel>/<contract route>`: the path after `/api/` (or `/v1/chain/`) a contract is served at. */\nexport const CHAIN_CONTRACT_OPERATION_PREFIXES = {\n 'asset/public-key-contract': 'asset-channel_basic-asset_PublicKeyContract',\n 'asset/token-contract': 'asset-channel_basic-asset_GalaChainToken',\n 'asset/fee-contract': 'asset-channel_basic-asset_GalaChainFee',\n 'asset/launchpad-contract': 'asset-channel_basic-asset_Launchpad',\n 'asset/dexv3-contract': 'asset-channel_basic-asset_DexV3Contract',\n 'asset/dex-contract': 'asset-channel_basic-asset_GalaChainDex',\n 'asset/registrar-contract': 'asset-channel_basic-asset_RegistrarContract',\n 'asset/staking-contract': 'asset-channel_basic-asset_StakingContract',\n 'asset/wallet-attributes-contract': 'asset-channel_basic-asset_WalletAttributesContract',\n 'asset/bridge-contract': 'asset-channel_bridge-chaincode_BridgeContract',\n 'asset/bridge-public-key-contract': 'asset-channel_bridge-chaincode_PublicKeyContract',\n 'asset/alm-contract': 'asset-channel_basic-asset_ALMContract',\n 'spidertanks/contract': 'spidertanks-channel_spidertanks_SpiderTanks',\n 'music/public-key-contract': 'music_music_PublicKeyContract',\n 'music/music-contract': 'music_music_GalaMusic',\n 'music/token-contract': 'music_music_GalaChainToken',\n 'pokergo/pokergo-contract': 'pokergo_pokergo_PokerGo',\n 'pokergo/public-key-contract': 'pokergo_pokergo_PublicKeyContract',\n 'pokergo/token-contract': 'pokergo_pokergo_GalaChainToken',\n 'championsarena/public-key-contract': 'championsarena_championsarena_PublicKeyContract',\n 'championsarena/champions-arena': 'championsarena_championsarena_ChampionsArenaContract',\n 'championsarena/token-contract': 'championsarena_championsarena_GalaChainToken',\n 'superior/public-key-contract': 'superior_superior_PublicKeyContract',\n 'superior/token-contract': 'superior_superior_GalaChainToken',\n 'superior/superior': 'superior_superior_Product',\n 'legacy/public-key-contract': 'legacy_legacy_PublicKeyContract',\n 'legacy/token-contract': 'legacy_legacy_GalaChainToken',\n 'legacy/legacy': 'legacy_legacy_Legacy',\n 'eternalparadox/public-key-contract': 'eternalparadox_eternalparadox_PublicKeyContract',\n 'eternalparadox/token-contract': 'eternalparadox_eternalparadox_GalaChainToken',\n 'eternalparadox/eternalparadox': 'eternalparadox_eternalparadox_EternalParadox',\n 'echoesofempire/public-key-contract': 'echoesofempire_echoesofempire_PublicKeyContract',\n 'echoesofempire/token-contract': 'echoesofempire_echoesofempire_GalaChainToken',\n 'echoesofempire/echoesofempire-contract': 'echoesofempire_echoesofempire_EchoesOfEmpire',\n 'node/public-key-contract': 'node_node_PublicKeyContract',\n 'node/token-contract': 'node_node_GalaChainToken',\n 'node/node-contract': 'node_node_Product',\n 'townstar/product-contract': 'townstar_townstar_TownStar',\n 'townstar/token-contract': 'townstar_townstar_GalaChainToken',\n 'townstar/public-key-contract': 'townstar_townstar_PublicKeyContract',\n 'mirandus/public-key-contract': 'mirandus_mirandus_PublicKeyContract',\n 'mirandus/token-contract': 'mirandus_mirandus_GalaChainToken',\n 'mirandus/mirandus-contract': 'mirandus_mirandus_Product',\n 'galafilm/public-key-contract': 'galafilm_galafilm_PublicKeyContract',\n 'galafilm/token-contract': 'galafilm_galafilm_GalaChainToken',\n 'galafilm/galafilm-contract': 'galafilm_galafilm_Product',\n 'lastexpedition/public-key-contract': 'lastexpedition_lastexpedition_PublicKeyContract',\n 'lastexpedition/token-contract': 'lastexpedition_lastexpedition_GalaChainToken',\n 'lastexpedition/lastexpedition-contract': 'lastexpedition_lastexpedition_Product',\n 'legendsreborn/public-key-contract': 'legendsreborn_legendsreborn_PublicKeyContract',\n 'legendsreborn/token-contract': 'legendsreborn_legendsreborn_GalaChainToken',\n 'legendsreborn/legendsreborn-contract': 'legendsreborn_legendsreborn_Product',\n 'thewalkingdeadempires/public-key-contract':\n 'thewalkingdeadempires_thewalkingdeadempires_PublicKeyContract',\n 'thewalkingdeadempires/token-contract':\n 'thewalkingdeadempires_thewalkingdeadempires_GalaChainToken',\n 'thewalkingdeadempires/thewalkingdeadempires-contract':\n 'thewalkingdeadempires_thewalkingdeadempires_Product',\n 'vox/public-key-contract': 'vox_vox_PublicKeyContract',\n 'vox/token-contract': 'vox_vox_GalaChainToken',\n 'vox/auction-contract': 'vox_vox_AuctionContract',\n 'vox/phase-contract': 'vox_vox_PhaseContract',\n 'vox/vox-contract': 'vox_vox_VOXTokenContract',\n 'vox/resources-contract': 'vox_vox_VOXResourceToken',\n} as const;\n\n/** An API path of a GalaChain contract (`asset/token-contract`, `asset/dex-contract`, ...). */\nexport type ChainContractPath = keyof typeof CHAIN_CONTRACT_OPERATION_PREFIXES;\n\n/** The `dtoOperation` of `method` on the contract served at `contractPath`. */\nexport function dtoOperationOf(contractPath: ChainContractPath, method: string): string {\n return `${CHAIN_CONTRACT_OPERATION_PREFIXES[contractPath]}:${method}`;\n}\n\n/**\n * `dto` with its `dtoOperation` set for `method` on `contractPath`. A DTO that already names a\n * different operation is refused: it was built for another call, and sending it would be rejected\n * by the chain after the signer had already signed it.\n *\n * @throws GalaSDKError SIGNING_FAILED when `dto.dtoOperation` is set and is not the operation of this call.\n */\nexport function withDtoOperation<T extends Record<string, unknown>>(\n contractPath: ChainContractPath,\n method: string,\n dto: T,\n): T & { readonly dtoOperation: string } {\n const dtoOperation = dtoOperationOf(contractPath, method);\n const present = dto['dtoOperation'];\n if (present !== undefined && present !== dtoOperation) {\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n { method, reason: 'failed' },\n { cause: { dtoOperation: present, expected: dtoOperation } },\n );\n }\n return { ...dto, dtoOperation };\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","import { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport type { GalaChainSigner, SignedDto } from '../classes/signers.js';\nimport { withDtoOperation, type ChainContractPath } from './dto_operation.js';\nimport { isWalletUserRejection, walletDeclineCode } from './wallet_rejection.js';\n\n/**\n * The boundary of \"nothing was sent\". Every place where an SDK hands control to code the APP\n * supplied BEFORE the request leaves (the signer here; a product SDK's token resolver) goes through\n * such a wrapper, so a failure of that code reaches the caller as a catalogued, pre-send SDK error\n * with the original as `cause`, never as a bare value the SDK cannot classify. An SDK error thrown\n * by that code is already catalogued and passes through untouched. Nothing here is used after the\n * request has been sent: an app's own rejection AFTER send stays what it is, because the SDK\n * cannot know what the server did with the write.\n */\n\n/**\n * Signs a DTO with the app's signer, after setting its `dtoOperation` to the operation of `method`\n * on the contract at `contractPath` (the chain refuses a DTO signed for another operation). Whatever the signer throws that is not already an SDK error\n * (a locked wallet, an unreachable extension, a wallet that declined) is `SIGNING_FAILED`\n * (`reason` `user_rejected` or `failed`, the original as `cause`), and a signer that returns\n * something other than an object is `SIGNING_FAILED` too: both are pre-send, so a retry is safe.\n * An SDK error of ANY product (every one is a `GalaSDKError`) passes through as it is.\n *\n * @throws GalaSDKError SIGNING_FAILED, or the SDK error the signer itself threw.\n */\nexport async function signPreSend<T extends Record<string, unknown>>(\n signer: GalaChainSigner,\n contractPath: ChainContractPath,\n method: string,\n dto: T,\n): Promise<SignedDto<T>> {\n let signed: SignedDto<T>;\n try {\n signed = await signer.signObject(method, withDtoOperation(contractPath, method, dto));\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n const reason = isWalletUserRejection(cause) ? 'user_rejected' : 'failed';\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n { method, reason },\n { cause, walletCode: walletDeclineCode(cause) },\n );\n }\n if (typeof signed !== 'object' || signed === null) {\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause: signed });\n }\n return signed;\n}\n","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.2';\n","import type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { GalaSDKError, isGalaError, parseJson } from '../classes/gala_sdk_error.js';\nimport { GALA_CORE_SDK_VERSION } from '../version.js';\n\n/**\n * Arms the abort timer for a request. `Infinity` means \"never time out\": `setTimeout` would turn\n * it into 1 ms, so no timer is armed at all. Returns a function that disarms it.\n */\nexport function armTimeout(controller: AbortController, timeoutMs: number): () => void {\n if (timeoutMs === Infinity) return () => undefined;\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return () => clearTimeout(timer);\n}\n\n/**\n * Validates a request timeout in milliseconds: a positive finite number, or `Infinity` for none.\n *\n * @throws GalaSDKError `INVALID_TIMEOUT` (`params.field` = `name`) otherwise.\n */\nexport function validateTimeoutMs(timeoutMs: number, name: string): number {\n if (timeoutMs === Infinity || (Number.isFinite(timeoutMs) && timeoutMs > 0)) return timeoutMs;\n throw new GalaSDKError('INVALID_TIMEOUT', { field: name, value: timeoutMs });\n}\n\nconst READABLE_QUERY_SAFE = /[A-Za-z0-9\\-._~!'()*$|:,]/u;\n\nfunction encodeReadable(text: string): string {\n let out = '';\n for (const char of text) {\n if (char === ' ') out += '+';\n else if (READABLE_QUERY_SAFE.test(char)) out += char;\n else out += encodeScalar(char);\n }\n return out;\n}\n\n/** Percent-encodes one code point; a lone surrogate becomes U+FFFD, as `URLSearchParams` does. */\nfunction encodeScalar(char: string): string {\n try {\n return encodeURIComponent(char);\n } catch {\n return '%EF%BF%BD';\n }\n}\n\n/** Serializes GET parameters, in insertion order, in the encoding the wire options select. */\nexport function buildQueryString(\n params: Record<string, string>,\n encoding: WireOptions['queryEncoding'] = 'standard',\n): string {\n if (encoding === 'readable') {\n return Object.entries(params)\n .map(([key, value]) => `${encodeReadable(key)}=${encodeReadable(value)}`)\n .join('&');\n }\n return new URLSearchParams(params).toString();\n}\n\n/** What an SDK request adds to the headers the wire options describe. */\nexport interface RequestHeaderParts {\n /** The request carries a JSON body: `Content-Type: application/json` unless `wire.headers` sets one. */\n json?: boolean | undefined;\n /** Headers the SDK sends unless `wire.headers` replaces them (for example `Accept`). */\n defaults?: Record<string, string> | undefined;\n /**\n * Headers that carry the request's meaning (`X-Wallet-Address`, `X-Shadow`). They come last and\n * replace a same-named `wire.headers` entry, so an app's static headers can never re-attribute\n * or un-shadow a write.\n */\n fixed?: Record<string, string> | undefined;\n}\n\n/**\n * The request headers for ANY SDK request, GET or POST, from one place so the wire options reach\n * every request alike. Order, which is the order the requestor sees them in: `User-Agent`\n * (`wire.userAgent`, default `GalaChain-SDK/<version>`, `false` omits it), `parts.defaults`,\n * `wire.headers`, `Content-Type` (JSON bodies only), `parts.fixed`. A later entry replaces an\n * earlier one of the same name regardless of case, so a header is never sent twice.\n */\nexport function buildRequestHeaders(\n wire: WireOptions | undefined,\n parts: RequestHeaderParts = {},\n): Record<string, string> {\n const entries = new Map<string, [name: string, value: string]>();\n const put = (headers: Record<string, string> | undefined, last = false): void => {\n for (const [name, value] of Object.entries(headers ?? {})) {\n // A fixed header leaves any earlier same-named entry behind, so it also keeps its place at the end.\n if (last) entries.delete(name.toLowerCase());\n entries.set(name.toLowerCase(), [name, value]);\n }\n };\n if (wire?.userAgent !== false) {\n put({ 'User-Agent': wire?.userAgent ?? `GalaChain-SDK/${GALA_CORE_SDK_VERSION}` });\n }\n put(parts.defaults);\n put(wire?.headers);\n if (parts.json === true && !entries.has('content-type')) {\n put({ 'Content-Type': 'application/json' });\n }\n put(parts.fixed, true);\n return Object.fromEntries(entries.values());\n}\n\n/**\n * The default requestor: the global `fetch`, with a failure before any answer (offline, DNS,\n * CORS) coded as `TRANSPORT_ERROR` and the original error kept as `cause`. An aborted request is\n * left to {@link requestWithTimeout}, which knows whether the timeout or the caller aborted it.\n * A requestor the app supplies is not wrapped: its rejection reaches the caller unchanged.\n */\nexport const fetchRequestor: HttpRequestor = async (url, init) => {\n try {\n return await fetch(url, init);\n } catch (error: unknown) {\n if (init?.signal?.aborted === true) throw error;\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause: error });\n }\n};\n\n/** What a request is, for the failures the transport raises itself (see {@link requestWithTimeout}). */\nexport interface RequestKind {\n /** `false` for a read: nothing it sends is applied, so its failures say `write: false`. */\n write: boolean;\n}\n\n/**\n * Sends one request through `requestor`, aborting it after `timeoutMs` (`REQUEST_TIMEOUT`). The\n * caller's own abort passes through as it is. `kind: { write: false }` marks a read: its\n * `REQUEST_TIMEOUT`, and a `TRANSPORT_ERROR` of the default requestors (which cannot tell a read\n * from a write), then say `write: false`. Without it they are judged as a write's (fail-closed),\n * which is what a write's transport needs before it decides what an unanswered write means.\n */\nexport async function requestWithTimeout(\n requestor: HttpRequestor,\n url: string,\n options: RequestInit,\n timeoutMs: number,\n kind?: RequestKind,\n): Promise<HTTPResponse> {\n const controller = new AbortController();\n const disarm = armTimeout(controller, timeoutMs);\n const externalSignal = options.signal;\n const abortFromCaller = (): void => controller.abort();\n externalSignal?.addEventListener('abort', abortFromCaller, { once: true });\n const read = kind?.write === false;\n try {\n return await requestor(url, { ...options, signal: controller.signal });\n } catch (error: unknown) {\n // The caller's own abort is theirs: it passes through as the abort it is, never as a timeout.\n if (externalSignal?.aborted === true) throw error;\n if (controller.signal.aborted) {\n throw new GalaSDKError(\n 'REQUEST_TIMEOUT',\n { url, timeoutMs },\n { url, cause: error, ...(read ? { write: false } : {}) },\n );\n }\n if (read && isGalaError(error, 'TRANSPORT_ERROR') && error.write) {\n throw new GalaSDKError(\n 'TRANSPORT_ERROR',\n { url: error.url ?? url },\n { url: error.url ?? url, cause: error.cause, write: false },\n );\n }\n // Anything else is the requestor's own rejection (an app's axios interceptor error, say):\n // rethrown as it is, because the app's error handling produced it.\n throw error;\n } finally {\n disarm();\n externalSignal?.removeEventListener('abort', abortFromCaller);\n }\n}\n\nexport async function readResponseBody(response: HTTPResponse): Promise<unknown> {\n const text = await response.text();\n return parseJson(text) ?? text;\n}\n\n/** Read a case-insensitive response header from either supported header shape. */\nexport function readHeader(response: HTTPResponse, name: string): string | undefined {\n const headers = response.headers;\n if (headers === undefined) return undefined;\n if (hasHeaderGetter(headers)) {\n const value = headers.get(name);\n return value === null || value === '' ? undefined : value;\n }\n const value = Object.entries(headers).find(\n ([key]) => key.toLowerCase() === name.toLowerCase(),\n )?.[1];\n return value === undefined || value === '' ? undefined : value;\n}\n\n/** Read a Retry-After header (delta-seconds or an HTTP date) as non-negative milliseconds. */\nexport function readRetryAfter(response: HTTPResponse): number | undefined {\n const raw = readHeader(response, 'retry-after');\n if (raw === undefined) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const timestamp = Date.parse(raw);\n return Number.isNaN(timestamp) ? undefined : Math.max(0, timestamp - Date.now());\n}\n\n/** Read a non-negative integer block number header. */\nexport function readBlockNumberHeader(\n response: HTTPResponse,\n headerName = 'x-block-number',\n): number | undefined {\n const raw = readHeader(response, headerName);\n if (raw === undefined) return undefined;\n const blockNumber = Number(raw);\n return Number.isInteger(blockNumber) && blockNumber >= 0 ? blockNumber : undefined;\n}\n\nfunction hasHeaderGetter(\n headers: NonNullable<HTTPResponse['headers']>,\n): headers is { get(name: string): string | null } {\n return 'get' in headers && typeof headers.get === 'function';\n}\n","import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport type { HttpRequestor, HTTPResponse } from '../types/http_requestor.js';\n\n/** What the adapter reads of an axios response. */\nexport interface AxiosLikeResponse {\n status: number;\n data?: unknown;\n /** axios' `AxiosHeaders` (has `get`) or a plain header record. */\n headers?: unknown;\n}\n\n/** The request config the adapter hands to axios. */\nexport interface AxiosLikeConfig {\n headers: Record<string, string>;\n signal?: AbortSignal;\n validateStatus?: () => boolean;\n}\n\n/**\n * The part of an axios instance the adapter calls. Declared structurally, so the SDK takes no\n * dependency on axios and any axios instance (with its interceptors) satisfies it.\n */\nexport interface AxiosLikeInstance {\n get(url: string, config?: AxiosLikeConfig): Promise<unknown>;\n post(url: string, data?: unknown, config?: AxiosLikeConfig): Promise<unknown>;\n}\n\n/** Options of {@link httpRequestorFromAxios}. */\nexport interface AxiosRequestorOptions {\n /**\n * `true`: leave axios' default status validation alone, so a 4xx/5xx REJECTS through the\n * instance's own interceptors and the SDK rethrows what the app's error handling produced.\n * `false`: every HTTP status resolves, so the SDK classifies it itself (shadow submits,\n * apply-results reads); transport failures still reject.\n */\n rejectOnHttpError: boolean;\n /**\n * Request headers NOT to hand to axios, matched case-insensitively. Default `['content-type']`:\n * axios derives `Content-Type: application/json` from the object body it is given, and an\n * interceptor may set its own, so the SDK's copy would only be a second opinion.\n */\n omitHeaders?: readonly string[] | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * An axios interceptor may resolve something that is not a response at all (for example a string\n * for ECONNREFUSED). That is a transport failure, not an HTTP answer.\n */\nfunction isAxiosLikeResponse(value: unknown): value is AxiosLikeResponse {\n return isRecord(value) && typeof value['status'] === 'number';\n}\n\nfunction readAxiosHeader(headers: unknown, name: string): string | null {\n if (!isRecord(headers)) return null;\n const getter = headers['get'];\n if (typeof getter === 'function') {\n const value: unknown = getter.call(headers, name);\n return typeof value === 'string' ? value : null;\n }\n const match = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase());\n return typeof match?.[1] === 'string' ? match[1] : null;\n}\n\nfunction toHttpResponse(answer: unknown, url: string): HTTPResponse {\n if (!isAxiosLikeResponse(answer)) {\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url });\n }\n const { status, data, headers } = answer;\n return {\n ok: status >= 200 && status < 300,\n status,\n json: () => Promise.resolve(data),\n text: () => Promise.resolve(typeof data === 'string' ? data : JSON.stringify(data)),\n headers: { get: (name: string) => readAxiosHeader(headers, name) },\n };\n}\n\nfunction headersFor(\n init: RequestInit | undefined,\n omit: readonly string[],\n): Record<string, string> {\n const omitted = new Set(omit.map((name) => name.toLowerCase()));\n const raw = init?.headers;\n const entries: Array<[string, string]> =\n raw === undefined\n ? []\n : raw instanceof Headers\n ? [...raw.entries()]\n : Array.isArray(raw)\n ? raw.map(([name, value]): [string, string] => [String(name), String(value)])\n : Object.entries(raw).map(([name, value]): [string, string] => [name, String(value)]);\n return Object.fromEntries(entries.filter(([name]) => !omitted.has(name.toLowerCase())));\n}\n\n/**\n * An SDK {@link HttpRequestor} over an axios instance, so the SDK's requests travel through the\n * app's own base URL, interceptors and error handling.\n *\n * A POST's string body is parsed back to the object the SDK serialized it from (axios serializes\n * again, and an interceptor may read the object); a GET goes through `instance.get`. The answer\n * is an HTTP response whose `json()`/`text()` read `response.data`. An answer that is not an\n * axios response is a `TRANSPORT_ERROR` rejection, and so is a rejection that means no HTTP\n * answer arrived (the original error is `cause`): any rejection with `rejectOnHttpError: false`\n * (every status resolves there), an axios error without a `response` with `true`. Any other\n * rejection (an interceptor's error for a 4xx, say) is rethrown unchanged, and so is an abort.\n *\n * Pair it with `ChainGateway`'s `dexBackendBaseUrl: ''` when the instance owns the base URL.\n *\n * @example\n * ```ts\n * const submitGateway = new ChainGateway({\n * dexBackendBaseUrl: '',\n * httpRequestor: httpRequestorFromAxios(chainGatewayInstance, { rejectOnHttpError: true }),\n * });\n * ```\n */\nexport function httpRequestorFromAxios(\n instance: AxiosLikeInstance,\n options: AxiosRequestorOptions,\n): HttpRequestor {\n const omit = options.omitHeaders ?? ['content-type'];\n return async (uri, init) => {\n const signal = init?.signal ?? undefined;\n const config: AxiosLikeConfig = {\n headers: headersFor(init, omit),\n ...(signal ? { signal } : {}),\n ...(options.rejectOnHttpError ? {} : { validateStatus: () => true }),\n };\n const isPost = (init?.method ?? 'GET').toUpperCase() === 'POST';\n const body: unknown =\n isPost && typeof init?.body === 'string' ? JSON.parse(init.body) : undefined;\n let answer: unknown;\n try {\n answer = await (isPost ? instance.post(uri, body, config) : instance.get(uri, config));\n } catch (error: unknown) {\n // An abort is the caller's or the SDK's timeout, and the request layer knows which.\n if (signal?.aborted === true || !isTransportRejection(error, options.rejectOnHttpError)) {\n throw error;\n }\n throw new GalaSDKError('TRANSPORT_ERROR', { url: uri }, { url: uri, cause: error });\n }\n return toHttpResponse(answer, uri);\n };\n}\n\n/**\n * Whether an axios rejection means no HTTP answer arrived. With `rejectOnHttpError: false` every\n * status resolves, so any rejection is one. With `true`, a 4xx/5xx rejects too, so only an axios\n * error that carries no `response` is (an interceptor's own error is an app answer and passes\n * through; an app whose interceptors turn network errors into their own class names it in\n * `ChainGatewayOptions.isTransportFailure`).\n */\nfunction isTransportRejection(error: unknown, rejectOnHttpError: boolean): boolean {\n if (!rejectOnHttpError) return true;\n return isRecord(error) && error['isAxiosError'] === true && error['response'] === undefined;\n}\n","import type { BrowserWalletProvider } from '../classes/signers.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { stripEip712DomainType } from './chain_dto_signing.js';\n\n/**\n * The part of an ethers v6 signer (`JsonRpcSigner`, `Wallet`) the adapter calls. Declared\n * structurally, so the SDK takes no dependency on ethers and an ethers object satisfies it as is.\n */\nexport interface EthersLikeSigner {\n signTypedData(\n domain: Record<string, unknown>,\n types: Record<string, Array<{ name: string; type: string }>>,\n value: Record<string, unknown>,\n ): Promise<string>;\n signMessage(message: string): Promise<string>;\n}\n\n/** The part of an ethers v6 provider (`BrowserProvider`) the adapter calls. */\nexport interface EthersLikeProvider {\n getSigner(): Promise<EthersLikeSigner>;\n /** The raw JSON-RPC passthrough (`BrowserProvider.send`). */\n send(method: string, params: unknown[]): Promise<unknown>;\n}\n\n/** Options of {@link eip1193ProviderFromEthers}. */\nexport interface EthersEip1193Options {\n /**\n * Signs a `personal_sign` message when the provider cannot or should not: a wallet SDK that\n * signs through its own object (TrustWallet's `web3Wallet.signMessage`). When set it answers\n * every `personal_sign`, and the provider is not touched for it.\n */\n personalSign?: ((message: string) => Promise<string>) | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isTypedDataTypes(\n value: unknown,\n): value is Record<string, Array<{ name: string; type: string }>> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (fields) =>\n Array.isArray(fields) &&\n fields.every(\n (field) =>\n isRecord(field) &&\n typeof field['name'] === 'string' &&\n typeof field['type'] === 'string',\n ),\n )\n );\n}\n\nfunction malformed(method: string): GalaSDKError {\n return new GalaSDKError('MALFORMED_WALLET_REQUEST', { method });\n}\n\n/** Splits `eth_signTypedData_v4` params (`[account, JSON payload]`) into what ethers' signer takes. */\nfunction readTypedDataRequest(params: unknown[] | undefined): {\n domain: Record<string, unknown>;\n types: Record<string, Array<{ name: string; type: string }>>;\n message: Record<string, unknown>;\n} {\n const raw = params?.[1];\n let payload: unknown;\n try {\n payload = typeof raw === 'string' ? JSON.parse(raw) : raw;\n } catch {\n throw malformed('eth_signTypedData_v4');\n }\n if (!isRecord(payload)) throw malformed('eth_signTypedData_v4');\n const { domain, types, message } = payload;\n if (!isRecord(domain) || !isTypedDataTypes(types) || !isRecord(message)) {\n throw malformed('eth_signTypedData_v4');\n }\n // ethers refuses an explicit EIP712Domain type; the JSON-RPC form includes it.\n return { domain, types: stripEip712DomainType(types), message };\n}\n\n/**\n * An EIP-1193 provider over an ethers v6 provider, for {@link BrowserWalletSigner}: apps whose\n * wallet connection is an ethers `BrowserProvider` sign through the very ethers calls they always\n * made, with no hand-written shim.\n *\n * - `eth_chainId` is `provider.send('eth_chainId', [])`: the wallet's LIVE chain. Never\n * `provider.getNetwork()`, which ethers caches and does not invalidate on `chainChanged`, so a\n * user who switches networks after connecting would sign against a stale chainId.\n * - `eth_signTypedData_v4` parses the `[account, JSON]` params and calls\n * `signer.signTypedData(domain, types, message)` with `EIP712Domain` removed from `types`.\n * - `personal_sign` is `options.personalSign(message)` when given, else `signer.signMessage`.\n * - Anything else is `UNSUPPORTED_WALLET_METHOD`; a malformed request is\n * `MALFORMED_WALLET_REQUEST`; a missing provider is `WALLET_UNAVAILABLE`.\n *\n * `provider` may be `null`/`undefined` (nothing connected): a request that needs it then fails\n * with `WALLET_UNAVAILABLE` rather than at construction, so a signer can be built before the\n * connection state is known.\n *\n * @example\n * ```ts\n * const signer = new BrowserWalletSigner(eip1193ProviderFromEthers(browserProvider), account, {\n * scheme: 'eip712',\n * });\n * ```\n */\nexport function eip1193ProviderFromEthers(\n provider: EthersLikeProvider | null | undefined,\n options: EthersEip1193Options = {},\n): BrowserWalletProvider {\n const connected = (): EthersLikeProvider => {\n if (provider === null || provider === undefined) {\n throw new GalaSDKError('WALLET_UNAVAILABLE', {});\n }\n return provider;\n };\n return {\n request: async ({ method, params }) => {\n switch (method) {\n case 'eth_chainId':\n return connected().send('eth_chainId', []);\n case 'eth_signTypedData_v4': {\n const wallet = connected();\n const { domain, types, message } = readTypedDataRequest(params);\n return (await wallet.getSigner()).signTypedData(domain, types, message);\n }\n case 'personal_sign': {\n const message = params?.[0];\n if (typeof message !== 'string') throw malformed('personal_sign');\n if (options.personalSign !== undefined) return options.personalSign(message);\n return (await connected().getSigner()).signMessage(message);\n }\n default:\n throw new GalaSDKError('UNSUPPORTED_WALLET_METHOD', { method });\n }\n },\n };\n}\n","/**\n * True when a rejection of a `fetch`-based requestor means NO HTTP ANSWER ARRIVED: the network\n * failed, the connection was reset, the host did not resolve, CORS blocked it. For a write that\n * is not a refusal (the request may have been queued), so this is the default\n * `ChainGatewayOptions.isTransportFailure` for a requestor that wraps `fetch` and rejects with\n * its own errors.\n *\n * - Yes: a `TypeError` (what `fetch` rejects with in every engine: `Failed to fetch`, `Load failed`,\n * `NetworkError when attempting to fetch resource`, undici's `fetch failed`), recognised by name\n * too so one from another realm (an extension page, an iframe) still counts, and a\n * `DOMException` named `NetworkError`.\n * - No: an abort (`AbortError`) or a timeout (`TimeoutError`). The SDK's own request layer knows\n * whether its timer or the caller's signal aborted, and reports those itself\n * (`REQUEST_TIMEOUT`, or the caller's own abort unchanged); claiming them here would turn the\n * caller's cancel into \"maybe queued\".\n * - No: anything else, including an SDK error and a value that is not an object.\n *\n * It never throws.\n *\n * @example\n * ```ts\n * new ChainGateway({ dexBackendBaseUrl, httpRequestor: galaFetch, isTransportFailure: isFetchTransportFailure });\n * ```\n */\nexport function isFetchTransportFailure(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n try {\n const name: unknown = 'name' in error ? error.name : undefined;\n if (name === 'AbortError' || name === 'TimeoutError') return false;\n return error instanceof TypeError || name === 'TypeError' || name === 'NetworkError';\n } catch {\n // A hostile or revoked object (a Proxy that throws on property access) proves nothing.\n return false;\n }\n}\n","/**\n * What a failure means for the operation that raised it, as one vocabulary for every app.\n *\n * - `rejected`: the CHAIN refused the request (a definite no). Nothing was applied, so a NEW\n * request is safe.\n * - `unknown`: the request MAY have been applied (a timeout, a broken connection, an\n * acknowledgement that proves nothing, a failed confirmation). Never submit again under a fresh\n * key: keep `error.uniqueKey` and confirm it.\n * - `not_queued`: the gateway refused the write before queueing it. Nothing is pending.\n * - `not_sent`: the request never left (`error.phase === 'pre_send'`) for a reason outside the\n * call itself: the signer or the wallet failed (locked, unreachable, the person declined), the\n * key provider or the token resolver failed, or no key was available yet. Nothing is pending and\n * nothing was transmitted, so repeating the call is safe and may succeed once the cause (an\n * unlocked wallet) is gone.\n * - `invalid_input`: the call itself cannot work (a bad argument, a missing signer or wallet, an\n * unknown token or pool, a corrupt stored key). Repeating the same call fails the same way.\n * Such an error is also pre-send (`isPreSendError`), but the input is what has to change.\n * - `transient`: a read or connection failed with no state change. Repeating the same call is safe\n * and may succeed.\n *\n * This module has no imports: the failure view (`FailureView.outcome`) and the classifier both\n * read the closed set from here.\n */\nexport const FAILURE_OUTCOMES = [\n 'rejected',\n 'unknown',\n 'not_queued',\n 'not_sent',\n 'invalid_input',\n 'transient',\n] as const;\n\n/** One member of {@link FAILURE_OUTCOMES}. */\nexport type FailureOutcome = (typeof FAILURE_OUTCOMES)[number];\n","import { GALA_ERROR_PHASES, type GalaErrorPhase } from '../classes/error_phases.js';\nimport { FAILURE_OUTCOMES, type FailureOutcome } from './failure_outcomes.js';\n\n/**\n * A failure as a PLAIN OBJECT: the facts the SDKs' guards and classifiers (gswap-sdk's\n * `classifyFailure`) read, and nothing else. A real `GalaSDKError` is one (every field below is on\n * it, and on every product subclass); so is the wrapper an app makes from an SDK error to carry\n * through its own layers (an app's own failure class or error data), which\n * has a `code` and `params` but is not an `instanceof` anything the SDK owns. gswap-sdk's\n * `classifyFailure`, `isRelayableRefusal`, `isUnprovenAcknowledgement`, `isUninterpretedAnswer`,\n * `isPreSendError`, `isShadowError`, `isNoMarket` and `mayHaveBeenQueued` all accept such an\n * object wherever they accept an SDK error, and decide from the SAME fields in the same way, so an\n * app never has to keep the original error just to ask.\n *\n * Only `code` is required. A field that is missing, or has the wrong type, reads as absent: a view\n * with no `status` is not a 404. Nothing here is text: the SDK never reads `message` of a view.\n *\n * READ OR WRITE: a view is a WRITE's unless it says it is a read. This fails CLOSED on purpose:\n * a 5xx on a write may have been queued (`unknown`, no retry) and the same 5xx on a read changed\n * nothing (`transient`, retry), so a wrapper that drops its `uniqueKey` must never turn the first\n * into the second. A view is a read ONLY when it states `write: false` and has no `uniqueKey`;\n * `GalaSDKError.write` is already set that way for every SDK read. {@link isWriteView}\n * is the one definition.\n *\n * APP ERRORS: a code the SDK catalog does not define is `unknown` (the SDK cannot say what\n * happened, and a wrong \"failed\" invites a duplicate), unless the view declares `outcome`.\n */\nexport interface FailureView {\n /** The catalog code (`'HTTP_ERROR'`, `'CHAIN_REJECTED'`, ...). A string the SDK does not know classifies as `unknown`. */\n readonly code: string;\n /** The error's flat params (`status` of an `HTTP_ERROR`, `reason` of a `SIGNING_FAILED`, ...). */\n readonly params?: Readonly<Record<string, unknown>> | undefined;\n /** The HTTP status of the answer the failure was made from. */\n readonly status?: number | undefined;\n /** How far the request got; when absent, the catalog's phase for `code`. */\n readonly phase?: GalaErrorPhase | undefined;\n /** The `uniqueKey` of the WRITE this is about; its presence makes the failure a write's. */\n readonly uniqueKey?: string | undefined;\n /**\n * `false` says the failed call was a READ (no `uniqueKey` to confirm, nothing pending). Anything\n * else, including absent, is a write: see the note on {@link FailureView}. With a `uniqueKey`\n * the failure is a write whatever this says.\n */\n readonly write?: boolean | undefined;\n /**\n * What an error the APP raised means, for a `code` the SDK catalog does not define (`'POSITION_STALE'`,\n * `'AMOUNT_SIDE'`): `not_sent` for a step that failed before anything was signed or sent, and so\n * on. The SDK honours it ONLY for such a code: for a catalog code the SDK's own table decides, so\n * an app cannot declare a refusal the SDK knows to be unknown as safe. A non-catalog code with no\n * `outcome` stays `unknown`, and `mayHaveBeenQueued` is then `true`.\n */\n readonly outcome?: FailureOutcome | undefined;\n /**\n * WITHHOLD-ONLY: `false` takes Retry away from the declared `outcome` (an app's `DID_NOT_QUEUE`\n * is `{ outcome: 'not_queued', retryable: false }`, the SDK's `NOT_QUEUED_FINAL`). Any other\n * value, `true` included, reads as absent: a view can never GRANT Retry to an outcome that does\n * not have it, and it is read only together with `outcome`, for a code the catalog does not\n * define.\n */\n readonly retryable?: false | undefined;\n /** True when the failure came from the shadow (dark) path. */\n readonly shadow?: boolean | undefined;\n /** True for \"that thing does not exist\" (`GalaSDKError.notFound`: a market, for gswap-sdk). */\n readonly notFound?: boolean | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Reads the failure view of any value: a `GalaSDKError`, or a plain object with a string `code`\n * (and, optionally, `params`, `status`, `phase`, `uniqueKey`, `shadow`, `notFound`). Anything else\n * (a string, a wallet error with a numeric `code`, `null`) has no view and is `undefined`.\n *\n * Having a view does not mean the SDK knows the code: an ethers error is `{ code:\n * 'ACTION_REJECTED' }` and has a view too. The SDK's guards compare the code with the catalog.\n *\n * @example\n * ```ts\n * const view = toFailureView(error); // an SDK error, or an app's `{ code, params, status }` wrapper\n * if (view?.code === 'CHAIN_REJECTED') showChainRejection(view.params);\n * ```\n */\nexport function toFailureView(value: unknown): FailureView | undefined {\n if (!isRecord(value)) return undefined;\n const { code, params, status, phase, uniqueKey, write, outcome, retryable, shadow, notFound } =\n value;\n if (typeof code !== 'string' || code === '') return undefined;\n return {\n code,\n params: isRecord(params) && !Array.isArray(params) ? params : undefined,\n status: typeof status === 'number' && Number.isFinite(status) ? status : undefined,\n phase: GALA_ERROR_PHASES.find((known) => known === phase),\n uniqueKey: typeof uniqueKey === 'string' && uniqueKey !== '' ? uniqueKey : undefined,\n write: typeof write === 'boolean' ? write : undefined,\n outcome: FAILURE_OUTCOMES.find((known) => known === outcome),\n retryable: retryable === false ? false : undefined,\n shadow: typeof shadow === 'boolean' ? shadow : undefined,\n notFound: typeof notFound === 'boolean' ? notFound : undefined,\n };\n}\n\n/**\n * True when a failure is a WRITE's: it names a `uniqueKey`, or it does not say `write: false`.\n * Fail-closed (see {@link FailureView}): only an explicit read is a read.\n */\nexport function isWriteView(view: FailureView): boolean {\n return view.uniqueKey !== undefined || view.write !== false;\n}\n\n/** A param of a view, when it is a string. */\nexport function stringParamOf(view: FailureView, name: string): string | undefined {\n const value = view.params?.[name];\n return typeof value === 'string' ? value : undefined;\n}\n\n/** A param of a view, when it is a finite number. */\nexport function numberParamOf(view: FailureView, name: string): number | undefined {\n const value = view.params?.[name];\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n","import type { GalaChainTokenClassKey } from '../types/token.js';\n\n/**\n * Token class keys that never throw: the `$`-joined composite key and the non-throwing parsers.\n * This module imports nothing at run time (the key type is erased), so an app shell that reads a\n * stored key pays for a few hundred bytes, never for the error class or the catalog. The parser\n * that THROWS an SDK error on a bad key (gswap-sdk's `parseTokenClassKey`) splits with\n * {@link splitClassKey} too, so the two can never disagree about a key.\n */\n\n/** Return the `$`-joined composite key used by GalaChain object identities. */\nexport function compositeKeyOf(token: GalaChainTokenClassKey): string {\n return [token.collection, token.category, token.type, token.additionalKey].join('$');\n}\n\n/**\n * Splits `collection<d>category<d>type<d>additionalKey` from the right, or `undefined` when there\n * are fewer than four segments or any of the four is empty. The one place the split is written;\n * the strict `parseTokenClassKey` calls it too.\n *\n * The LAST three segments are always `category`, `type` and `additionalKey`; everything before\n * them is the `collection`. Parsing from the right is required because real collections contain\n * the `$` delimiter themselves (for example `$GMUSIC`), so a plain left-to-right `split('$')`\n * shifts every field.\n */\nexport function splitClassKey(\n key: string,\n delimiter: '|' | '$',\n): GalaChainTokenClassKey | undefined {\n const segments = key.split(delimiter);\n const tail = segments.slice(-3);\n const collection = segments.slice(0, -3).join(delimiter);\n if (segments.length < 4 || collection.length === 0 || tail.some((part) => part.length === 0)) {\n return undefined;\n }\n const [category, type, additionalKey] = tail;\n return {\n collection,\n category: category as string,\n type: type as string,\n additionalKey: additionalKey as string,\n };\n}\n\n/**\n * The non-throwing `parseTokenClassKey`: the class key, or `undefined` when `value` is not\n * one. A string is split exactly as `parseTokenClassKey` splits it (`|` form when it contains a\n * `|`, else `$`, from the right, all four parts non-empty). Unlike `parseTokenClassKey`, an\n * object is VALIDATED, not just copied: all four fields must be non-empty strings. Anything else\n * (`undefined`, `null`, a number, an array) is `undefined`, so it is safe on untrusted input (a\n * stored token, a URL parameter, a wallet row) without a `try`/`catch`.\n *\n * Use {@link tryParseCompositeKey} instead when only the `$` form is valid input.\n *\n * @example\n * ```ts\n * const key = tryParseTokenClassKey(row.compositeKey);\n * if (key === undefined) return failClosed(); // no class is known: never invent one from a symbol\n * ```\n */\nexport function tryParseTokenClassKey(value: unknown): GalaChainTokenClassKey | undefined {\n if (typeof value === 'string') return splitClassKey(value, value.includes('|') ? '|' : '$');\n if (typeof value !== 'object' || value === null) return undefined;\n try {\n const { collection, category, type, additionalKey } = value as Record<string, unknown>;\n if (\n typeof collection !== 'string' ||\n typeof category !== 'string' ||\n typeof type !== 'string' ||\n typeof additionalKey !== 'string' ||\n collection === '' ||\n category === '' ||\n type === '' ||\n additionalKey === ''\n ) {\n return undefined;\n }\n return { collection, category, type, additionalKey };\n } catch {\n // A getter or proxy that throws is not a token class key.\n return undefined;\n }\n}\n\n/**\n * True for a token class key OBJECT: `collection`, `category`, `type` and `additionalKey` are all\n * non-empty strings (other fields, an `instance` say, are allowed). A string is never one: parse it\n * with {@link tryParseTokenClassKey}. Never throws (a getter that throws is \"not a key\").\n *\n * @example\n * ```ts\n * if (isTokenClassKey(value)) console.log(compositeKeyOf(value));\n * ```\n */\nexport function isTokenClassKey(value: unknown): value is GalaChainTokenClassKey {\n return typeof value === 'object' && value !== null && tryParseTokenClassKey(value) !== undefined;\n}\n\n/**\n * Parses a `$`-joined composite key (`Collection$Category$Type$AdditionalKey`, what\n * {@link compositeKeyOf} writes) and nothing else, or `undefined`. It is {@link tryParseTokenClassKey}\n * for a string that may ONLY be in the `$` form: a key that contains `|` is NOT read as the pipe\n * form here (it stays part of a segment), and only a string is accepted. The split is from the\n * right, so a collection that itself contains `$` (production's `$GMUSIC`, stage's\n * `$GMUSIC_TEST1`) stays whole; `'GALA'`, `'GALA$Unit$none'`, `'ETIME$$$'`, `'GALA$Unit$none$'` and\n * `'$$$$'` are `undefined`.\n *\n * It replaces an app's own `parseCompositeKey(key): Components | null` (`?? null`), which had\n * exactly these semantics.\n *\n * @example\n * ```ts\n * tryParseCompositeKey('$GMUSIC_TEST1$Unit$none$none')?.collection; // '$GMUSIC_TEST1'\n * tryParseCompositeKey('GALA$Unit$none'); // undefined\n * ```\n */\nexport function tryParseCompositeKey(value: unknown): GalaChainTokenClassKey | undefined {\n return typeof value === 'string' ? splitClassKey(value, '$') : undefined;\n}\n","/**\n * The shape of a write `uniqueKey`, with NO imports: the pending-swap store and the failure guards\n * need only this check, and importing it from `unique_key.ts` would drag in `GalaSDKError` and the\n * whole error catalog for it.\n */\n\n/** The swap backend's apply-results key constraint (`apply-results.dto.ts`). */\nconst UNIQUE_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;\n\n/**\n * True when `uniqueKey` is a usable write key: 1 to 128 characters of `A-Za-z0-9._:-`, the shape\n * the apply-results route accepts. The one definition behind `assertUniqueKey`, `confirm()` and\n * the pending-swap store, so they can never disagree about what a valid key is.\n */\nexport function isValidUniqueKey(uniqueKey: unknown): uniqueKey is string {\n return typeof uniqueKey === 'string' && UNIQUE_KEY_PATTERN.test(uniqueKey);\n}\n","import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { isValidUniqueKey } from './unique_key_syntax.js';\n\n/**\n * The `uniqueKey` prefix the Gala Wallet and the gSwap web app have always sent\n * (`galaswap-operation-<uuid>`). The backend does not depend on it: the chain-write verifier\n * only requires a non-empty key of at most 256 characters, and apply-results accepts\n * `[A-Za-z0-9._:-]{1,128}`; the only code that mints a prefixed key itself is the server-side v1\n * trade builder, which nothing reads back by prefix.\n */\nexport const DEFAULT_UNIQUE_KEY_PREFIX = 'galaswap-operation-';\n\n/** Options shared by the services that mint `uniqueKey`s for writes. */\nexport interface UniqueKeyOptions {\n /**\n * Prefix of every minted `uniqueKey` (`<prefix><uuid>`). Defaults to\n * `DEFAULT_UNIQUE_KEY_PREFIX` (`galaswap-operation-`).\n */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/** A canonical UUID is 36 characters; the apply-results key limit is 128. */\nconst MAX_UNIQUE_KEY_PREFIX_LENGTH = 128 - 36;\nconst UNIQUE_KEY_PREFIX_PATTERN = /^[A-Za-z0-9._:-]*$/u;\n\n/**\n * Validates a caller-supplied `uniqueKey` prefix. The whole key (`<prefix><uuid>`) must stay a\n * valid apply-results key, otherwise `confirm()` could never read the outcome of the write.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY_PREFIX` when the prefix has characters outside\n * `A-Za-z0-9._:-` or is longer than 92 characters.\n */\nexport function resolveUniqueKeyPrefix(prefix: string | undefined): string {\n if (prefix === undefined) return DEFAULT_UNIQUE_KEY_PREFIX;\n if (!UNIQUE_KEY_PREFIX_PATTERN.test(prefix) || prefix.length > MAX_UNIQUE_KEY_PREFIX_LENGTH) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY_PREFIX', {\n uniqueKeyPrefix: prefix,\n maxLength: MAX_UNIQUE_KEY_PREFIX_LENGTH,\n });\n }\n return prefix;\n}\n\n/**\n * Validates a caller-supplied write `uniqueKey`: 1 to 128 characters of `A-Za-z0-9._:-`, the\n * shape the apply-results route accepts, so the write's outcome can always be read back with\n * `confirm()`. A key is one attempt's identity: reuse it only to retry that same attempt.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY` otherwise.\n */\nexport function assertUniqueKey(uniqueKey: string): void {\n if (!isValidUniqueKey(uniqueKey)) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY', { uniqueKey: String(uniqueKey) });\n }\n}\n\n/** The part of `globalThis.crypto` a uniqueKey needs: the one CSPRNG every target can offer. */\ninterface RandomValuesSource {\n getRandomValues?: ((array: Uint8Array) => unknown) | undefined;\n}\n\n/**\n * A random version-4 UUID (RFC 9562) in the canonical lowercase `8-4-4-4-12` form, byte for byte\n * the shape `crypto.randomUUID()` returns, built from `crypto.getRandomValues`. `randomUUID` is\n * NOT used: React Native's Hermes has no `crypto.randomUUID`, so a write would fail with\n * \"undefined is not a function\", while `getRandomValues` is what browsers, Node (>= 19 as a\n * global), MV3 service workers and Hermes with `react-native-get-random-values` all provide.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when there is no `getRandomValues`: a key minted from\n * `Math.random` could collide with another attempt's, so the SDK refuses rather than degrade.\n */\nfunction randomUuidV4(): string {\n const source = (globalThis as { crypto?: RandomValuesSource | undefined }).crypto;\n if (typeof source?.getRandomValues !== 'function') {\n throw new GalaSDKError('CSPRNG_UNAVAILABLE', {});\n }\n // Filled in place: a polyfill is not relied on to return the array.\n const bytes = new Uint8Array(16);\n source.getRandomValues(bytes);\n const hex: string[] = [];\n bytes.forEach((byte, index) => {\n // Version nibble 4 in byte 6, variant bits 10 in byte 8; everything else stays random.\n const value = index === 6 ? (byte & 0x0f) | 0x40 : index === 8 ? (byte & 0x3f) | 0x80 : byte;\n hex.push(value.toString(16).padStart(2, '0'));\n });\n const text = hex.join('');\n return [\n text.slice(0, 8),\n text.slice(8, 12),\n text.slice(12, 16),\n text.slice(16, 20),\n text.slice(20),\n ].join('-');\n}\n\n/**\n * A fresh per-attempt key: `<prefix><random UUID>`, the UUID a random version-4 one.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when the platform has no `crypto.getRandomValues`\n * (install a polyfill such as `react-native-get-random-values` on React Native).\n */\nexport function createUniqueKey(prefix: string): string {\n return `${prefix}${randomUuidV4()}`;\n}\n","/**\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","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","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","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","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","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","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","import BigNumber from 'bignumber.js';\nimport type {\n GalaChainNftCollectionAuthorization,\n GalaChainPage,\n GalaChainPublicKey,\n GalaChainTokenBalance,\n GalaChainTokenClass,\n GalaChainTokenHold,\n} from './types.js';\n\n/**\n * Readers of the chain's answers. Each returns the typed value, or `undefined` when the value is\n * not what GalaChain answers (the caller turns that into `GATEWAY_READ_RESPONSE_INVALID`), so an\n * answer is never half-trusted: a balance with a numeric quantity, a hold without its expiry or a\n * token class without its symbol is refused whole, never passed on with a hole in it.\n */\n\ntype Row = Readonly<Record<string, unknown>>;\n\nfunction isRow(value: unknown): value is Row {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value !== '';\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\n/** A non-negative amount as the chain writes it: a decimal string `bignumber.js` reads exactly. */\nfunction isAmount(value: unknown): value is string {\n if (typeof value !== 'string' || value.trim() !== value || value === '') return false;\n const amount = new BigNumber(value);\n return amount.isFinite() && !amount.isNegative();\n}\n\nfunction stringList(value: unknown): string[] | undefined {\n return Array.isArray(value) && value.every(isString) ? [...value] : undefined;\n}\n\n/** A list of `parse`d entries, `undefined` when it is not a list or any entry is unusable. */\nfunction listOf<T>(value: unknown, parse: (entry: unknown) => T | undefined): T[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const parsed: T[] = [];\n for (const entry of value) {\n const item = parse(entry);\n if (item === undefined) return undefined;\n parsed.push(item);\n }\n return parsed;\n}\n\n/** An optional field: absent or `undefined` is fine, present must pass `check`. */\nfunction optional<T>(\n row: Row,\n key: string,\n check: (value: unknown) => value is T,\n): T | undefined | null {\n const value = row[key];\n if (value === undefined) return undefined;\n return check(value) ? value : null;\n}\n\nexport function parseHold(value: unknown): GalaChainTokenHold | undefined {\n if (!isRow(value)) return undefined;\n const { created, createdBy, expires, instanceId, lockAuthority, quantity } = value;\n const name = optional(value, 'name', isString);\n const vestingPeriodStart = optional(value, 'vestingPeriodStart', isFiniteNumber);\n if (\n !isFiniteNumber(created) ||\n !isString(createdBy) ||\n !isFiniteNumber(expires) ||\n !isString(instanceId) ||\n !isString(lockAuthority) ||\n !isAmount(quantity) ||\n name === null ||\n vestingPeriodStart === null\n ) {\n return undefined;\n }\n return {\n created,\n createdBy,\n expires,\n instanceId,\n lockAuthority,\n ...(name === undefined ? {} : { name }),\n quantity,\n ...(vestingPeriodStart === undefined ? {} : { vestingPeriodStart }),\n };\n}\n\n/** A hold list that the chain may leave out (older balances have no `inUseHolds`). */\nfunction holdsOf(value: unknown): GalaChainTokenHold[] | undefined {\n return value === undefined ? [] : listOf(value, parseHold);\n}\n\nexport function parseBalance(value: unknown): GalaChainTokenBalance | undefined {\n if (!isRow(value)) return undefined;\n const { owner, collection, category, type, additionalKey, quantity } = value;\n const instanceIds = value['instanceIds'] === undefined ? [] : stringList(value['instanceIds']);\n const lockedHolds = holdsOf(value['lockedHolds']);\n const inUseHolds = holdsOf(value['inUseHolds']);\n if (\n !isNonEmptyString(owner) ||\n !isNonEmptyString(collection) ||\n !isNonEmptyString(category) ||\n !isNonEmptyString(type) ||\n !isNonEmptyString(additionalKey) ||\n !isAmount(quantity) ||\n instanceIds === undefined ||\n lockedHolds === undefined ||\n inUseHolds === undefined\n ) {\n return undefined;\n }\n return {\n owner,\n collection,\n category,\n type,\n additionalKey,\n quantity,\n instanceIds,\n lockedHolds,\n inUseHolds,\n };\n}\n\nexport function parseBalances(value: unknown): GalaChainTokenBalance[] | undefined {\n return listOf(value, parseBalance);\n}\n\n/** The required string fields of a token class, in the order the chain serializes them. */\nconst CLASS_STRINGS = [\n 'collection',\n 'category',\n 'type',\n 'additionalKey',\n 'network',\n 'maxSupply',\n 'maxCapacity',\n 'name',\n 'symbol',\n 'description',\n 'image',\n 'totalBurned',\n 'totalMintAllowance',\n 'totalSupply',\n] as const;\n\n/** The optional string fields of a token class (`FetchTokenClassesWithSupply` adds the two supplies). */\nconst CLASS_OPTIONAL_STRINGS = [\n 'contractAddress',\n 'metadataAddress',\n 'rarity',\n 'quantityLimit',\n 'knownMintSupply',\n 'knownMintAllowanceSupply',\n] as const;\n\nconst CLASS_KEY_PARTS: ReadonlySet<string> = new Set([\n 'collection',\n 'category',\n 'type',\n 'additionalKey',\n]);\n\nexport function parseTokenClass(value: unknown): GalaChainTokenClass | undefined {\n if (!isRow(value)) return undefined;\n const strings: Record<string, string> = {};\n for (const key of CLASS_STRINGS) {\n const field = value[key];\n if (!isString(field) || (CLASS_KEY_PARTS.has(key) && field === '')) return undefined;\n strings[key] = field;\n }\n const extras: Record<string, string> = {};\n for (const key of CLASS_OPTIONAL_STRINGS) {\n const field = optional(value, key, isString);\n if (field === null) return undefined;\n if (field !== undefined) extras[key] = field;\n }\n const { decimals, isNonFungible } = value;\n const authorities = stringList(value['authorities']);\n if (\n typeof decimals !== 'number' ||\n !Number.isSafeInteger(decimals) ||\n decimals < 0 ||\n typeof isNonFungible !== 'boolean' ||\n authorities === undefined\n ) {\n return undefined;\n }\n return {\n ...strings,\n decimals,\n isNonFungible,\n authorities,\n ...extras,\n } as unknown as GalaChainTokenClass;\n}\n\nexport function parseTokenClasses(value: unknown): GalaChainTokenClass[] | undefined {\n return listOf(value, parseTokenClass);\n}\n\nexport function parseNftCollectionAuthorization(\n value: unknown,\n): GalaChainNftCollectionAuthorization | undefined {\n if (!isRow(value)) return undefined;\n const { collection } = value;\n const authorizedUsers = stringList(value['authorizedUsers']);\n if (!isNonEmptyString(collection) || authorizedUsers === undefined) return undefined;\n return { collection, authorizedUsers };\n}\n\n/** A registered public key (`GetPublicKey`): a non-empty `publicKey`, and `signing` when present. */\nexport function parsePublicKey(value: unknown): GalaChainPublicKey | undefined {\n if (!isRow(value)) return undefined;\n const { publicKey } = value;\n const signing = optional(value, 'signing', isNonEmptyString);\n if (!isNonEmptyString(publicKey) || signing === null) return undefined;\n return { publicKey, ...(signing === undefined ? {} : { signing }) };\n}\n\n/** A paginated answer (`{ results, nextPageBookmark }`); an empty bookmark means the last page. */\nexport function parsePage<T>(\n value: unknown,\n parse: (entry: unknown) => T | undefined,\n): GalaChainPage<T> | undefined {\n if (!isRow(value)) return undefined;\n const results = listOf(value['results'], parse);\n const bookmark = optional(value, 'nextPageBookmark', isString);\n if (results === undefined || bookmark === null) return undefined;\n return { results, nextPageBookmark: bookmark === '' ? undefined : bookmark };\n}\n","import { GalaSDKError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { buildRequestHeaders, readResponseBody, requestWithTimeout } from '../utils/transport.js';\nimport type { GatewayReadMethod } from './types.js';\n\n/** What every read is sent with. */\nexport interface ReadTransport {\n readonly gatewayBaseUrl: string;\n readonly requestor: HttpRequestor;\n readonly timeoutMs: number;\n readonly wire: WireOptions | undefined;\n}\n\n/** The gateway channel a token lives on. */\nexport type GatewayChannel = 'asset' | 'music';\n\n/** The chaincode contract each read method belongs to (part of its URL). */\nconst CONTRACT_OF: Readonly<Record<GatewayReadMethod, 'token-contract' | 'public-key-contract'>> = {\n FetchBalances: 'token-contract',\n FetchTokenClasses: 'token-contract',\n FetchTokenClassesWithSupply: 'token-contract',\n FetchTokenClassesWithPagination: 'token-contract',\n FetchNftCollectionAuthorizationsWithPagination: 'token-contract',\n GetPublicKey: 'public-key-contract',\n};\n\n/**\n * Methods whose successful answer carries no `Status`: the connect-api GalaChain proxies answer\n * `GetPublicKey` with `{ Data: { publicKey } }` only (recorded 2026-10-14, prod and stage,\n * `tests/fixtures/public-key-recorded.json`). A `Status` they do send is still checked.\n */\nconst ANSWERED_WITHOUT_STATUS: ReadonlySet<GatewayReadMethod> = new Set<GatewayReadMethod>([\n 'GetPublicKey',\n]);\n\n/**\n * The channel of a collection: `$MUSIC` (and `MUSIC`, any case) lives on the gateway's `music`\n * channel, every other collection (`$GMUSIC` included) on `asset`.\n */\nexport function channelOf(collection: string | undefined): GatewayChannel {\n return collection !== undefined && /^\\$?music$/iu.test(collection) ? 'music' : 'asset';\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\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 * The chain's error object of a refused answer: GalaChain's gateway nests it as\n * `{ error: { Status: 0, ErrorKey, Message, ErrorPayload }, message }`; an older answer carries\n * `Status` / `ErrorKey` / `Message` at the top.\n */\nexport function chainErrorOf(body: unknown): Record<string, unknown> | undefined {\n if (!isRecord(body)) return undefined;\n const nested = body['error'];\n return isRecord(nested) ? nested : body;\n}\n\n/**\n * POSTs one read and returns the chain's `Data`. Reads change nothing, so every failure is a READ's\n * (`error.write === false`) and a retry is always safe:\n *\n * - no answer: `REQUEST_TIMEOUT` / `TRANSPORT_ERROR`, both `write: false` (an app requestor's\n * own rejection passes through unchanged: it is the app's error); a body that broke off is\n * `TRANSPORT_ERROR`;\n * - a numeric top-level `Status` other than 1, in any HTTP status: `GATEWAY_READ_REJECTED`;\n * - any other non-2xx: `GATEWAY_HTTP_ERROR` (`params.status`; the chain's refusal is `error.body`);\n * - a 2xx that is not `{ Status: 1, Data }` (for `GetPublicKey`, whose answer carries no\n * `Status`, not `{ Data }`): `GATEWAY_READ_RESPONSE_INVALID`.\n */\nexport async function readGateway(\n transport: ReadTransport,\n method: GatewayReadMethod,\n body: Record<string, unknown>,\n channel: GatewayChannel = 'asset',\n): Promise<unknown> {\n const url = `${transport.gatewayBaseUrl}/api/${channel}/${CONTRACT_OF[method]}/${method}`;\n const response = await requestWithTimeout(\n transport.requestor,\n url,\n {\n method: 'POST',\n headers: buildRequestHeaders(transport.wire, { json: true }),\n body: JSON.stringify(body),\n },\n transport.timeoutMs,\n { write: false },\n );\n let answer: unknown;\n try {\n answer = await readResponseBody(response);\n } catch (cause: unknown) {\n // The answer's headers arrived and its body broke off: nothing usable was read.\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause, write: false });\n }\n return dataOf(method, url, response, answer);\n}\n\nfunction dataOf(\n method: GatewayReadMethod,\n url: string,\n response: HTTPResponse,\n answer: unknown,\n): unknown {\n const context: GalaErrorContext = { status: response.status, body: answer, url, write: false };\n const envelope = isRecord(answer) ? answer : undefined;\n const chainStatus = envelope?.['Status'];\n if (typeof chainStatus === 'number' && chainStatus !== 1) {\n throw new GalaSDKError(\n 'GATEWAY_READ_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 const chainError = chainErrorOf(answer);\n throw new GalaSDKError(\n 'GATEWAY_HTTP_ERROR',\n {\n method,\n status: response.status,\n serverMessage: stringField(chainError, 'Message') || stringField(envelope, 'message'),\n },\n context,\n );\n }\n const statusAccepted =\n chainStatus === 1 || (chainStatus === undefined && ANSWERED_WITHOUT_STATUS.has(method));\n if (envelope === undefined || !statusAccepted || !('Data' in envelope)) {\n throw new GalaSDKError('GATEWAY_READ_RESPONSE_INVALID', { method }, context);\n }\n return envelope['Data'];\n}\n\n/** The error for a 2xx whose `Data` is not what `method` answers. */\nexport function invalidAnswer(\n method: GatewayReadMethod,\n data: unknown,\n): GalaSDKError<'GATEWAY_READ_RESPONSE_INVALID'> {\n return new GalaSDKError(\n 'GATEWAY_READ_RESPONSE_INVALID',\n { method },\n { body: data, write: false },\n );\n}\n","import type { HttpRequestor } from '../types/http_requestor.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { WireOptions } from '../types/wire.js';\nimport type { TokenClassKeyInput } from '../writes/types.js';\n\n/**\n * The contract methods `GatewayReads` calls, as a closed set: the token-contract reads, and\n * `GetPublicKey` of the public-key-contract.\n */\nexport const GATEWAY_READ_METHODS = [\n 'FetchBalances',\n 'FetchTokenClasses',\n 'FetchTokenClassesWithSupply',\n 'FetchTokenClassesWithPagination',\n 'FetchNftCollectionAuthorizationsWithPagination',\n 'GetPublicKey',\n] as const;\n\n/** One member of {@link GATEWAY_READ_METHODS}. */\nexport type GatewayReadMethod = (typeof GATEWAY_READ_METHODS)[number];\n\n/**\n * The public key GalaChain has registered for a user (`GetPublicKey`), as the chain answers it.\n * `publicKey` is the chain's encoding (base64 of the compressed secp256k1 key); `signing` is the\n * signing scheme older chain versions store next to it (`'ETH'`, `'TON'`), absent on current ones.\n */\nexport interface GalaChainPublicKey {\n readonly publicKey: string;\n readonly signing?: string | undefined;\n}\n\n/**\n * The SDK's bounds on one read: at most `tokenClasses` keys per `fetchTokenClasses` /\n * `fetchTokenClassesWithSupply` request, at most `pageSize` results per page of a paginated read\n * (the chain's own maximum for its paginated token reads), and by default at most `maxPages`\n * pages per `fetchAll...` call.\n */\nexport const GATEWAY_READ_LIMITS = Object.freeze({\n tokenClasses: 1000,\n pageSize: 10_000,\n maxPages: 100,\n});\n\n/** How to reach the gateway for reads. Reads are unsigned: no signer is involved. */\nexport interface GatewayReadsOptions {\n /**\n * The GalaChain gateway base URL; every read POSTs to\n * `<gatewayBaseUrl>/api/<channel>/<contract>/<Method>` (`token-contract`, or\n * `public-key-contract` for `GetPublicKey`). `''` sends the bare path, for an `httpRequestor`\n * that resolves paths against its own base (an HTTP client with a base URL). The public gateways\n * do not route the public-key-contract; a connect-api's `.../galachain` proxy base does.\n */\n gatewayBaseUrl: string;\n /** The HTTP requestor; default the global `fetch`. Its own rejections reach the caller unchanged. */\n httpRequestor?: HttpRequestor | undefined;\n /** Timeout of every read request in milliseconds (default 30 000); `Infinity` arms no timer. */\n requestTimeoutMs?: number | undefined;\n /** Headers of every read request (`userAgent`, `headers`); see {@link WireOptions}. */\n wire?: WireOptions | undefined;\n}\n\n/**\n * A hold on part of a balance (a lock, or the legacy in-use hold), as GalaChain stores it.\n * `quantity` is whole tokens as a decimal string; times are epoch milliseconds.\n */\nexport interface GalaChainTokenHold {\n /** When the hold was placed. */\n readonly created: number;\n /** Who placed it. */\n readonly createdBy: string;\n /** When it expires; `0` means never. */\n readonly expires: number;\n /** The token instance held (`\"0\"` for a fungible token). */\n readonly instanceId: string;\n /** Who may release it. */\n readonly lockAuthority: string;\n /** The hold's name, when it has one. */\n readonly name?: string | undefined;\n /** How much is held, in whole tokens. */\n readonly quantity: string;\n /** Start of a vesting period, when the hold is a vesting hold. */\n readonly vestingPeriodStart?: number | undefined;\n}\n\n/** One balance record of `FetchBalances`: an owner's holding of one token class. */\nexport interface GalaChainTokenBalance extends GalaChainTokenClassKey {\n readonly owner: string;\n /** The holding in whole tokens, as the chain's decimal string (never scaled). */\n readonly quantity: string;\n /** The instance ids held, for a non-fungible token; empty for a fungible one. */\n readonly instanceIds: readonly string[];\n /** Locks on the holding. */\n readonly lockedHolds: readonly GalaChainTokenHold[];\n /** The legacy in-use holds (older balances only). */\n readonly inUseHolds: readonly GalaChainTokenHold[];\n}\n\n/**\n * What `fetchBalances` filters by. `owner` is required (without it the chain answers every\n * owner's balances); the class-key parts narrow the answer. A filter on `$MUSIC` or `MUSIC` is\n * sent to the gateway's `music` channel, where that collection lives; every other to `asset`.\n */\nexport interface BalancesFilter {\n /**\n * An Ethereum account (`eth|<40 hex>`, `0x<40 hex>` or `<40 hex>`, any casing but a wrong\n * EIP-55 checksum; always sent as `eth|<checksummed>`), or a `client|` alias (sent as written).\n * `eth|0x<40 hex>` is not an address form and is refused (`INVALID_ETH_USER_REF_PREFIX`). The\n * answer's records carry the owner as sent.\n */\n owner: string;\n collection?: string | undefined;\n category?: string | undefined;\n type?: string | undefined;\n additionalKey?: string | undefined;\n}\n\n/** `fetchTokenBalance`: one owner's balance of one token class, with its holds summed. */\nexport interface TokenBalanceInput {\n /** The owner (see {@link BalancesFilter.owner}). */\n owner: string;\n /** The token class (pipe string with exactly four parts, `$` composite key, or object). */\n tokenClassKey: TokenClassKeyInput;\n /** Keep holds that have expired (default `false`: an expired hold no longer holds anything). */\n includeExpiredHolds?: boolean | undefined;\n /** The time holds are judged at, in epoch milliseconds (default now). */\n asOf?: number | undefined;\n}\n\n/**\n * An owner's balance of one token class with its holds totalled. Every quantity is whole tokens as\n * a plain decimal string (no exponent), computed exactly (`bignumber.js`), never scaled.\n */\nexport interface GalaChainTokenBalanceSummary {\n readonly owner: string;\n readonly tokenClassKey: GalaChainTokenClassKey;\n /** The whole holding. */\n readonly quantity: string;\n /** The locks still in force (all of them with `includeExpiredHolds`). */\n readonly lockedHolds: readonly GalaChainTokenHold[];\n /** The in-use holds still in force (all of them with `includeExpiredHolds`). */\n readonly inUseHolds: readonly GalaChainTokenHold[];\n /** The sum of `lockedHolds`. */\n readonly lockedQuantity: string;\n /** The sum of `inUseHolds`. */\n readonly inUseQuantity: string;\n /** `quantity - lockedQuantity - inUseQuantity`. */\n readonly availableQuantity: string;\n /** The instance ids held (non-fungible tokens). */\n readonly instanceIds: readonly string[];\n}\n\n/**\n * A token class as GalaChain registers it. Supply figures are whole tokens as the chain's decimal\n * strings (`\"Infinity\"` for an uncapped capacity), never numbers.\n */\nexport interface GalaChainTokenClass extends GalaChainTokenClassKey {\n readonly network: string;\n readonly decimals: number;\n readonly maxSupply: string;\n readonly maxCapacity: string;\n readonly isNonFungible: boolean;\n readonly authorities: readonly string[];\n readonly name: string;\n readonly symbol: string;\n readonly description: string;\n readonly image: string;\n readonly totalBurned: string;\n readonly totalMintAllowance: string;\n readonly totalSupply: string;\n readonly contractAddress?: string | undefined;\n readonly metadataAddress?: string | undefined;\n readonly rarity?: string | undefined;\n readonly quantityLimit?: string | undefined;\n /** Supply figures `FetchTokenClassesWithSupply` adds. */\n readonly knownMintSupply?: string | undefined;\n readonly knownMintAllowanceSupply?: string | undefined;\n}\n\n/** The metadata of a token class an app shows: its key, symbol, decimals, name and image. */\nexport interface GalaChainTokenDetails extends GalaChainTokenClassKey {\n readonly symbol: string;\n readonly decimals: number;\n readonly name: string;\n readonly image: string;\n readonly description: string;\n readonly network: string;\n readonly contractAddress?: string | undefined;\n}\n\n/** What `fetchTokenClassesPage` / `fetchAllTokenClasses` filter by (any subset of a class key). */\nexport interface TokenClassesFilter {\n collection?: string | undefined;\n category?: string | undefined;\n type?: string | undefined;\n additionalKey?: string | undefined;\n}\n\n/** One page request of a paginated read. */\nexport interface PageInput {\n /** The `nextPageBookmark` of the previous page; omitted for the first page. */\n bookmark?: string | undefined;\n /** Results per page, 1 to `GATEWAY_READ_LIMITS.pageSize`; omitted: the chain's default. */\n limit?: number | undefined;\n}\n\n/** One page of a paginated read. */\nexport interface GalaChainPage<T> {\n readonly results: readonly T[];\n /** The bookmark of the next page, `undefined` on the last page. */\n readonly nextPageBookmark: string | undefined;\n}\n\n/** How a `fetchAll...` read walks the pages. */\nexport interface AllPagesOptions {\n /** Results per page (see {@link PageInput.limit}). */\n pageSize?: number | undefined;\n /**\n * The most pages it reads, 1 to 10 000 (default `GATEWAY_READ_LIMITS.maxPages`). A data set\n * with more pages is `PAGINATION_LIMIT_EXCEEDED`, never a silently truncated answer.\n */\n maxPages?: number | undefined;\n}\n\n/** Who may create token classes in an NFT collection. */\nexport interface GalaChainNftCollectionAuthorization {\n readonly collection: string;\n readonly authorizedUsers: readonly string[];\n}\n","import BigNumber from 'bignumber.js';\nimport { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport { compositeKeyOf } from '../utils/class_key.js';\nimport { fetchRequestor, validateTimeoutMs } from '../utils/transport.js';\nimport { galaChainUserRef } from '../writes/identity.js';\nimport { tokenClassKeyOf } from '../writes/token_ref.js';\nimport type { TokenClassKeyInput } from '../writes/types.js';\nimport {\n parseBalances,\n parseNftCollectionAuthorization,\n parsePage,\n parsePublicKey,\n parseTokenClass,\n parseTokenClasses,\n} from './parse.js';\nimport {\n channelOf,\n chainErrorOf,\n invalidAnswer,\n readGateway,\n type ReadTransport,\n} from './request.js';\nimport {\n GATEWAY_READ_LIMITS,\n type AllPagesOptions,\n type BalancesFilter,\n type GalaChainNftCollectionAuthorization,\n type GalaChainPage,\n type GalaChainPublicKey,\n type GalaChainTokenBalance,\n type GalaChainTokenBalanceSummary,\n type GalaChainTokenClass,\n type GalaChainTokenDetails,\n type GalaChainTokenHold,\n type GatewayReadMethod,\n type GatewayReadsOptions,\n type PageInput,\n type TokenBalanceInput,\n type TokenClassesFilter,\n} from './types.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\nconst MAX_PAGES_LIMIT = 10_000;\nconst KEY_PARTS = ['collection', 'category', 'type', 'additionalKey'] as const;\n\n/** The class-key parts a filter names, checked (each present one a non-empty string), in key order. */\nfunction filterParts(\n filter: Readonly<Record<string, unknown>>,\n at: string,\n): Partial<GalaChainTokenClassKey> {\n const parts: Partial<Record<(typeof KEY_PARTS)[number], string>> = {};\n for (const part of KEY_PARTS) {\n const value = filter[part];\n if (value === undefined) continue;\n if (typeof value !== 'string' || value === '') {\n throw new GalaSDKError('INVALID_TOKEN_REFERENCE', {\n field: `${at}${part}`,\n reason: 'bad_class_key',\n });\n }\n parts[part] = value;\n }\n return parts;\n}\n\n/** A page size or page count: a whole number from 1 to `max`, or `undefined` for the default. */\nfunction boundedCount(\n value: unknown,\n field: 'limit' | 'pageSize' | 'maxPages',\n max: number,\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 && value <= max) {\n return value;\n }\n // A number or string is shown as written; anything else by its type (never an object's text).\n const shown =\n typeof value === 'number' || typeof value === 'string'\n ? String(value)\n : value === null\n ? 'null'\n : typeof value;\n throw new GalaSDKError('INVALID_PAGE_REQUEST', { field, value: shown });\n}\n\nfunction sameKey(row: GalaChainTokenClassKey, key: GalaChainTokenClassKey): boolean {\n return KEY_PARTS.every((part) => row[part] === key[part]);\n}\n\n/**\n * The metadata an app shows for a token, from its token class: the key, symbol, decimals, name,\n * image, description, network and (when the class has one) contract address. A class key never\n * carries a symbol; this is where one comes from.\n */\nexport function tokenDetailsOf(tokenClass: GalaChainTokenClass): GalaChainTokenDetails {\n return {\n collection: tokenClass.collection,\n category: tokenClass.category,\n type: tokenClass.type,\n additionalKey: tokenClass.additionalKey,\n symbol: tokenClass.symbol,\n decimals: tokenClass.decimals,\n name: tokenClass.name,\n image: tokenClass.image,\n description: tokenClass.description,\n network: tokenClass.network,\n ...(tokenClass.contractAddress === undefined\n ? {}\n : { contractAddress: tokenClass.contractAddress }),\n };\n}\n\n/** The amount of `holds` together, exactly, as a plain decimal string. */\nfunction totalOf(holds: readonly GalaChainTokenHold[]): BigNumber {\n return holds.reduce((sum, hold) => sum.plus(hold.quantity), new BigNumber(0));\n}\n\n/**\n * Unsigned GalaChain token-contract reads through the gateway: balances (with their holds summed),\n * token classes (with or without supply, by key or page by page), token metadata and NFT\n * collection authorizations; and a user's registered public key (public-key-contract). React\n * Native safe (no Node builtins, no ethers, no `@gala-chain/api`).\n *\n * Every input is checked before anything is sent (owners as `GatewayWrites` spells them, class\n * keys in the forms a write accepts, page sizes), and every answer is checked before it is\n * trusted: GalaChain's `Status`, then each row's shape. Amounts stay the chain's whole-token\n * decimal strings (never scaled, never numbers). A read applies nothing, so a retry is always\n * safe: every failure after the request left says so (`error.write === false`), and an input\n * refused before it is `pre_send` (nothing was sent).\n *\n * @example\n * ```ts\n * const reads = new GatewayReads({ gatewayBaseUrl: 'https://gateway-mainnet.galachain.com' });\n * const gala = await reads.fetchTokenBalance({ owner: 'client|abc', tokenClassKey: 'GALA|Unit|none|none' });\n * console.log(gala?.availableQuantity);\n * ```\n */\nexport class GatewayReads {\n private readonly transport: ReadTransport;\n\n /**\n * @throws GalaSDKError `INVALID_READS_OPTION` (a missing base URL, a requestor that is not a\n * function), `INVALID_TIMEOUT`.\n */\n constructor(options: GatewayReadsOptions) {\n const { gatewayBaseUrl, httpRequestor } = options;\n if (typeof gatewayBaseUrl !== 'string') {\n throw new GalaSDKError('INVALID_READS_OPTION', { option: 'gatewayBaseUrl' });\n }\n if (httpRequestor !== undefined && typeof httpRequestor !== 'function') {\n throw new GalaSDKError('INVALID_READS_OPTION', { option: 'httpRequestor' });\n }\n this.transport = {\n gatewayBaseUrl: gatewayBaseUrl.replace(/\\/+$/u, ''),\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 * The owner's balance records (`FetchBalances`), narrowed by any class-key parts given. Sent to\n * the `music` channel for `$MUSIC`, else `asset`. An answer with a record of another owner is\n * `GATEWAY_READ_RESPONSE_INVALID` (it is never reported as the owner's).\n *\n * @throws GalaSDKError pre-send: `INVALID_WALLET_ADDRESS` (`field: 'owner'`),\n * `INVALID_TOKEN_REFERENCE`; then the read failures (see the class note).\n */\n public async fetchBalances(filter: BalancesFilter): Promise<GalaChainTokenBalance[]> {\n const owner = galaChainUserRef(filter.owner, 'owner');\n const parts = filterParts(filter as unknown as Record<string, unknown>, '');\n const data = await readGateway(\n this.transport,\n 'FetchBalances',\n { owner, ...parts },\n channelOf(parts.collection),\n );\n const balances = parseBalances(data);\n // A record of anyone but the owner asked for is never reported as theirs.\n if (balances === undefined || balances.some((row) => row.owner !== owner)) {\n throw invalidAnswer('FetchBalances', data);\n }\n return balances;\n }\n\n /**\n * The owner's balance of one token class with its holds totalled, or `undefined` when the chain\n * has no balance record of it for the owner. Holds that have expired are dropped (they no longer\n * hold anything) unless `includeExpiredHolds`.\n *\n * @throws GalaSDKError as {@link fetchBalances}.\n */\n public async fetchTokenBalance(\n input: TokenBalanceInput,\n ): Promise<GalaChainTokenBalanceSummary | undefined> {\n const key = tokenClassKeyOf(input.tokenClassKey, 'tokenClassKey');\n const balance = (await this.fetchBalances({ owner: input.owner, ...key })).find((row) =>\n sameKey(row, key),\n );\n if (balance === undefined) return undefined;\n const now = Date.now();\n const inForce = (holds: readonly GalaChainTokenHold[]): GalaChainTokenHold[] =>\n input.includeExpiredHolds === true\n ? [...holds]\n : holds.filter((hold) => hold.expires === 0 || hold.expires > now);\n const lockedHolds = inForce(balance.lockedHolds);\n const inUseHolds = inForce(balance.inUseHolds);\n const locked = totalOf(lockedHolds);\n const inUse = totalOf(inUseHolds);\n return {\n owner: balance.owner,\n tokenClassKey: key,\n quantity: balance.quantity,\n lockedHolds,\n inUseHolds,\n lockedQuantity: locked.toFixed(),\n inUseQuantity: inUse.toFixed(),\n availableQuantity: new BigNumber(balance.quantity).minus(locked).minus(inUse).toFixed(),\n instanceIds: balance.instanceIds,\n };\n }\n\n /**\n * The owner's non-fungible holdings: the balance records that hold at least one instance.\n *\n * @throws GalaSDKError as {@link fetchBalances}.\n */\n public async fetchNftBalances(filter: BalancesFilter): Promise<GalaChainTokenBalance[]> {\n return (await this.fetchBalances(filter)).filter((row) => row.instanceIds.length > 0);\n }\n\n /**\n * The token classes of `tokenClassKeys` (`FetchTokenClasses`), one per key, in the order asked.\n *\n * @throws GalaSDKError pre-send: `INVALID_TOKEN_BATCH` (1 to `GATEWAY_READ_LIMITS.tokenClasses`\n * keys), `INVALID_TOKEN_REFERENCE`; `TOKEN_CLASS_NOT_FOUND` for a key the chain has no class\n * of; then the read failures.\n */\n public fetchTokenClasses(\n tokenClassKeys: readonly TokenClassKeyInput[],\n ): Promise<GalaChainTokenClass[]> {\n return this.readClasses('FetchTokenClasses', tokenClassKeys);\n }\n\n /**\n * As {@link fetchTokenClasses}, with the chain's supply figures (`knownMintSupply`,\n * `knownMintAllowanceSupply`) on each class (`FetchTokenClassesWithSupply`).\n */\n public fetchTokenClassesWithSupply(\n tokenClassKeys: readonly TokenClassKeyInput[],\n ): Promise<GalaChainTokenClass[]> {\n return this.readClasses('FetchTokenClassesWithSupply', tokenClassKeys);\n }\n\n /**\n * The token class of one key.\n *\n * @throws GalaSDKError as {@link fetchTokenClasses}.\n */\n public async fetchTokenClass(tokenClassKey: TokenClassKeyInput): Promise<GalaChainTokenClass> {\n const [tokenClass] = await this.readClasses('FetchTokenClasses', [tokenClassKey]);\n return tokenClass as GalaChainTokenClass;\n }\n\n /**\n * The metadata an app shows for a token (its key, symbol, decimals, name, image, description,\n * network and contract address), from its token class: the source of truth for a symbol, which\n * a class key never carries.\n *\n * @throws GalaSDKError as {@link fetchTokenClasses}.\n */\n public async fetchTokenDetails(\n tokenClassKey: TokenClassKeyInput,\n ): Promise<GalaChainTokenDetails> {\n return tokenDetailsOf(await this.fetchTokenClass(tokenClassKey));\n }\n\n /**\n * One page of the token classes matching `filter` (`FetchTokenClassesWithPagination`).\n *\n * @throws GalaSDKError pre-send: `INVALID_TOKEN_REFERENCE`, `INVALID_PAGE_REQUEST`; then the\n * read failures.\n */\n public async fetchTokenClassesPage(\n filter: TokenClassesFilter & PageInput = {},\n ): Promise<GalaChainPage<GalaChainTokenClass>> {\n const parts = filterParts(filter as unknown as Record<string, unknown>, '');\n return this.readPage('FetchTokenClassesWithPagination', parts, filter, parseTokenClass);\n }\n\n /**\n * Every token class matching `filter`, page by page, up to `maxPages` pages.\n *\n * @throws GalaSDKError as {@link fetchTokenClassesPage}, plus `PAGINATION_LIMIT_EXCEEDED`.\n */\n public async fetchAllTokenClasses(\n filter: TokenClassesFilter = {},\n options: AllPagesOptions = {},\n ): Promise<GalaChainTokenClass[]> {\n const parts = filterParts(filter as unknown as Record<string, unknown>, '');\n return this.readAllPages('FetchTokenClassesWithPagination', options, (page) =>\n this.readPage('FetchTokenClassesWithPagination', parts, page, parseTokenClass),\n );\n }\n\n /**\n * One page of the NFT collection authorizations (`FetchNftCollectionAuthorizationsWithPagination`):\n * which users may create token classes in which collection.\n *\n * @throws GalaSDKError pre-send: `INVALID_PAGE_REQUEST`; then the read failures.\n */\n public fetchNftCollectionAuthorizationsPage(\n page: PageInput = {},\n ): Promise<GalaChainPage<GalaChainNftCollectionAuthorization>> {\n return this.readPage(\n 'FetchNftCollectionAuthorizationsWithPagination',\n {},\n page,\n parseNftCollectionAuthorization,\n );\n }\n\n /**\n * Every NFT collection authorization, page by page, up to `maxPages` pages.\n *\n * @throws GalaSDKError as {@link fetchNftCollectionAuthorizationsPage}, plus\n * `PAGINATION_LIMIT_EXCEEDED`.\n */\n public fetchAllNftCollectionAuthorizations(\n options: AllPagesOptions = {},\n ): Promise<GalaChainNftCollectionAuthorization[]> {\n return this.readAllPages('FetchNftCollectionAuthorizationsWithPagination', options, (page) =>\n this.fetchNftCollectionAuthorizationsPage(page),\n );\n }\n\n /**\n * The public key GalaChain has registered for `user` (`GetPublicKey` of the\n * public-key-contract, `asset` channel), or `undefined` when the chain has none saved for that\n * user (its `PK_NOT_FOUND`). The public gateways do not route this contract: build the reads with\n * a connect-api `.../galachain` proxy base (`https://<connect-api>/galachain`), whose answer is\n * `{ Data: { publicKey } }` without a `Status` (a `Status` that is sent is still checked).\n *\n * @example\n * ```ts\n * const reads = new GatewayReads({ gatewayBaseUrl: 'https://api-galaswap.gala.com/galachain' });\n * const registered = await reads.fetchPublicKey('client|64f8caf887fd8551315d8509');\n * console.log(registered?.publicKey);\n * ```\n *\n * @throws GalaSDKError pre-send: `INVALID_WALLET_ADDRESS` (`field: 'user'`); then the read\n * failures (see the class note).\n */\n public async fetchPublicKey(user: string): Promise<GalaChainPublicKey | undefined> {\n const ref = galaChainUserRef(user, 'user');\n let data: unknown;\n try {\n data = await readGateway(this.transport, 'GetPublicKey', { user: ref });\n } catch (error: unknown) {\n if (isPublicKeyNotFound(error)) return undefined;\n throw error;\n }\n const publicKey = parsePublicKey(data);\n if (publicKey === undefined) throw invalidAnswer('GetPublicKey', data);\n return publicKey;\n }\n\n private async readClasses(\n method: 'FetchTokenClasses' | 'FetchTokenClassesWithSupply',\n tokenClassKeys: readonly TokenClassKeyInput[],\n ): Promise<GalaChainTokenClass[]> {\n const count = Array.isArray(tokenClassKeys) ? tokenClassKeys.length : 0;\n const max = GATEWAY_READ_LIMITS.tokenClasses;\n if (count < 1 || count > max) {\n throw new GalaSDKError('INVALID_TOKEN_BATCH', { method, count, max });\n }\n const keys = tokenClassKeys.map((key, index) =>\n tokenClassKeyOf(key, `tokenClassKeys[${index}]`),\n );\n let data: unknown;\n try {\n data = await readGateway(this.transport, method, { tokenClasses: keys });\n } catch (error: unknown) {\n throw notFoundOf(error) ?? error;\n }\n const rows = parseTokenClasses(data);\n if (rows === undefined) throw invalidAnswer(method, data);\n return keys.map((key) => {\n const row = rows.find((candidate) => sameKey(candidate, key));\n if (row === undefined) {\n throw new GalaSDKError(\n 'TOKEN_CLASS_NOT_FOUND',\n { tokenClassKey: compositeKeyOf(key) },\n { body: data, write: false },\n );\n }\n return row;\n });\n }\n\n private async readPage<T>(\n method: GatewayReadMethod,\n parts: Partial<GalaChainTokenClassKey>,\n page: PageInput,\n parse: (entry: unknown) => T | undefined,\n ): Promise<GalaChainPage<T>> {\n const limit = boundedCount(page.limit, 'limit', GATEWAY_READ_LIMITS.pageSize);\n const { bookmark } = page;\n if (bookmark !== undefined && typeof bookmark !== 'string') {\n throw new GalaSDKError('INVALID_PAGE_REQUEST', { field: 'bookmark', value: typeof bookmark });\n }\n const data = await readGateway(this.transport, method, {\n ...parts,\n ...(bookmark === undefined || bookmark === '' ? {} : { bookmark }),\n ...(limit === undefined ? {} : { limit }),\n });\n const parsed = parsePage(data, parse);\n if (parsed === undefined) throw invalidAnswer(method, data);\n return parsed;\n }\n\n /**\n * Reads page after page until the chain says there is none left. Bounded: a page whose bookmark\n * does not move on is an unusable answer (it would repeat forever), and a data set with more\n * than `maxPages` pages is `PAGINATION_LIMIT_EXCEEDED`, never a truncated list.\n */\n private async readAllPages<T>(\n method: GatewayReadMethod,\n options: AllPagesOptions,\n readPage: (page: PageInput) => Promise<GalaChainPage<T>>,\n ): Promise<T[]> {\n const maxPages =\n boundedCount(options.maxPages, 'maxPages', MAX_PAGES_LIMIT) ?? GATEWAY_READ_LIMITS.maxPages;\n const limit = boundedCount(options.pageSize, 'pageSize', GATEWAY_READ_LIMITS.pageSize);\n const results: T[] = [];\n let bookmark: string | undefined;\n for (let page = 0; page < maxPages; page += 1) {\n const answer = await readPage({\n ...(bookmark === undefined ? {} : { bookmark }),\n ...(limit === undefined ? {} : { limit }),\n });\n results.push(...answer.results);\n if (answer.nextPageBookmark === undefined) return results;\n if (answer.nextPageBookmark === bookmark) throw invalidAnswer(method, answer);\n bookmark = answer.nextPageBookmark;\n }\n throw new GalaSDKError('PAGINATION_LIMIT_EXCEEDED', { method, maxPages }, { write: false });\n }\n}\n\n/** The chain's \"no public key saved for this user\": HTTP 404 with `ErrorKey: PK_NOT_FOUND`. */\nfunction isPublicKeyNotFound(error: unknown): boolean {\n if (!isGalaError(error, 'GATEWAY_HTTP_ERROR') || error.status !== 404) return false;\n return chainErrorOf(error.body)?.['ErrorKey'] === 'PK_NOT_FOUND';\n}\n\n/**\n * The chain's \"no such token class\" (HTTP 404, `ErrorKey: TOKEN_CLASS_NOT_FOUND`) as\n * `TOKEN_CLASS_NOT_FOUND`, naming the key the chain named; `undefined` for any other failure.\n */\nfunction notFoundOf(error: unknown): GalaSDKError<'TOKEN_CLASS_NOT_FOUND'> | undefined {\n if (!isGalaError(error, 'GATEWAY_HTTP_ERROR') || error.status !== 404) return undefined;\n const chainError = chainErrorOf(error.body);\n if (chainError?.['ErrorKey'] !== 'TOKEN_CLASS_NOT_FOUND') return undefined;\n const payload = chainError['ErrorPayload'];\n const named =\n typeof payload === 'object' && payload !== null\n ? (payload as Record<string, unknown>)['tokenClassKey']\n : undefined;\n return new GalaSDKError(\n 'TOKEN_CLASS_NOT_FOUND',\n { tokenClassKey: typeof named === 'string' ? named : '' },\n { status: error.status, body: error.body, url: error.url, write: false, cause: error },\n );\n}\n","/** A GalaChain deployment: `prod` (mainnet) or `stage` (testnet). */\nexport type GalaChainEnv = 'prod' | 'stage';\n\n/** The product-independent endpoints of one GalaChain deployment. */\nexport interface GalaChainEnvironmentConfig {\n /** The public GalaChain gateway (`GatewayReads` / `GatewayWrites` `gatewayBaseUrl`). */\n readonly gatewayBaseUrl: string;\n /** The DEX API platform (GalaConnect: bridge, wrap and referral reads). */\n readonly dexApiBaseUrl: string;\n /**\n * The EIP-712 domain NAME the deployment's chain requires of a typed-data signature\n * (\"EIP-712 domain name must be GalaChainStage for this deployment. Received ethereum.\"). Pass\n * it to a signer's `eip712DomainName` option. Absent where the deployment accepts the name each\n * signer has always used (`prod`), so a signer given `undefined` signs exactly what it always\n * did.\n */\n readonly eip712DomainName?: string;\n}\n\n/**\n * The built-in endpoints of each deployment. A product SDK extends these with its own backends\n * (launchpad-sdk's launchpad and bundler URLs, gswap-sdk's swap backend); it never redefines them.\n */\nexport const GALA_CHAIN_ENVIRONMENTS: Readonly<Record<GalaChainEnv, GalaChainEnvironmentConfig>> =\n Object.freeze({\n prod: Object.freeze({\n gatewayBaseUrl: 'https://gateway-mainnet.galachain.com',\n dexApiBaseUrl: 'https://dex-api-platform-dex-prod-gala.gala.com',\n }),\n stage: Object.freeze({\n gatewayBaseUrl: 'https://gateway-testnet.galachain.com',\n dexApiBaseUrl: 'https://dex-api-platform-dex-stage-gala.gala.com',\n eip712DomainName: 'GalaChainStage',\n }),\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;AACF;;;;;;;;;;;AAeA,MAAa,0BAA0B,CAAC,iBAAiB,QAAQ;;;;;;;;;;;;;AAiBjE,MAAa,kCAAkC;CAC7C;CACA;CACA;CACA;AACF;;;;;;;AAWA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;AACF;;;;;;;;;;AAcA,MAAa,wCAAwC,CAAC,WAAW,WAAW;;;;;AAU5E,MAAa,wBAAwB,CAAC,kBAAkB,eAAe;;;;;;;;AAYvE,MAAa,sBAAsB;CAAC;CAAS;CAAY;CAAY;AAAU;;;;;;;;;;AAc/E,MAAa,+BAA+B;CAC1C;CACA;CACA;AACF;;;;;;;;AAYA,MAAa,oCAAoC;CAC/C;CACA;CACA;AACF;;;;;;;;AAYA,MAAa,iCAAiC,CAC5C,oBACA,iCACF;;;;;;;;;;;AAeA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;AACF;;AAMA,MAAa,kBAAkB,CAAC,YAAY,QAAQ;;;;;;;;AAYpD,MAAa,yBAAyB;CACpC;CACA;CACA;AACF;;;;;;;;;AAaA,MAAa,mBAAmB;CAAC;CAAc;CAAoB;AAAkB;;;;;;;;AAYrF,MAAa,uBAAuB;CAAC;CAAQ;CAAgB;AAAc;;;;;;;;AAY3E,MAAa,uBAAuB;CAAC;CAAc;CAAkB;AAAiB;;AAMtF,MAAa,kBAAkB,CAAC,QAAQ,QAAQ;;AAMhD,MAAa,qBA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AU,MAAM,cAAc,QAAQ,MAAM;GAC5E,WAAW,OAAO;EACpB;EACA,MAAM,IAAI,aAAa,6BAA6B;GAAE;GAAQ;EAAS,GAAG,EAAE,OAAO,MAAM,CAAC;CAC5F;AACF;;AAGA,SAAS,oBAAoB,OAAyB;;CACpD,IAAI,CAAC,YAAY,OAAO,oBAAoB,KAAK,MAAM,WAAW,KAAK,OAAO;CAC9E,yBAAO,aAAa,MAAM,IAAI,iEAAI,iBAAgB;AACpD;;;;;AAMA,SAAS,WAAW,OAAmE;CACrF,IAAI,CAAC,YAAY,OAAO,oBAAoB,KAAK,MAAM,WAAW,KAAK,OAAO;CAC9E,MAAM,aAAa,aAAa,MAAM,IAAI;CAC1C,6DAAI,WAAa,iBAAgB,yBAAyB,OAAO;CACjE,MAAM,UAAU,WAAW;CAC3B,MAAM,QACJ,OAAO,YAAY,YAAY,YAAY,OACtC,QAAoC,mBACrC;CACN,OAAO,IAAI,aACT,yBACA,EAAE,eAAe,OAAO,UAAU,WAAW,QAAQ,GAAG,GACxD;EAAE,QAAQ,MAAM;EAAQ,MAAM,MAAM;EAAM,KAAK,MAAM;EAAK,OAAO;EAAO,OAAO;CAAM,CACvF;AACF;;;;;;;;ACvcA,MAAa,0BACX,OAAO,OAAO;CACZ,MAAM,OAAO,OAAO;EAClB,gBAAgB;EAChB,eAAe;CACjB,CAAC;CACD,OAAO,OAAO,OAAO;EACnB,gBAAgB;EAChB,eAAe;EACf,kBAAkB;CACpB,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["isRecord","textEncoder","textEncoder","globalObject","isRecord","isRecord","isRecord","isRecord","stringField","DEFAULT_REQUEST_TIMEOUT_MS"],"sources":["../src/classes/error_catalog.ts","../src/classes/error_phase_table.ts","../src/classes/error_phases.ts","../src/utils/error_brand.ts","../src/classes/gala_sdk_error.ts","../src/utils/eth_address.ts","../src/writes/identity.ts","../src/utils/eip712.ts","../src/utils/signing.ts","../src/classes/signers.ts","../src/utils/chain_dto_signing.ts","../src/utils/typed_data.ts","../src/utils/dto_operation.ts","../src/utils/wallet_rejection.ts","../src/utils/pre_send.ts","../src/version.ts","../src/utils/transport.ts","../src/utils/axios_requestor.ts","../src/utils/ethers_provider.ts","../src/utils/fetch_failure.ts","../src/utils/failure_outcomes.ts","../src/utils/failure_view.ts","../src/utils/class_key.ts","../src/utils/unique_key_syntax.ts","../src/utils/unique_key.ts","../src/utils/wallet_keys.ts","../src/writes/lock.ts","../src/writes/submit.ts","../src/writes/token_ref.ts","../src/writes/transfer.ts","../src/writes/types.ts","../src/writes/gateway_writes.ts","../src/reads/parse.ts","../src/reads/request.ts","../src/reads/types.ts","../src/reads/gateway_reads.ts","../src/config/environments.ts"],"sourcesContent":["/**\n * The catalog of every error `@gala-chain/gala-core-sdk` throws: the SINGLE source of truth for\n * its `code`, the named parameters it carries and the English template its `message` is generated\n * from. A product SDK (gswap-sdk, launchpad-sdk) keeps its OWN catalog of the codes only it throws,\n * and its error class (a subclass of `GalaSDKError`) reads both; no code is defined twice.\n *\n * - `code` is the only discriminator. It is stable: apps branch on it, never on message text.\n * - `params` are the named placeholders of the error: a flat object of primitives (string,\n * number, boolean) that an app feeds to its own localization (i18next, ICU, FormatJS).\n * Raw server payloads are never params (they are `error.body` / `error.bodyText`), and no\n * secret (private key, signature, raw DTO) ever is.\n * - `template` is English with `{placeholder}` markers. `error.message` is generated from it\n * and the params, so the two cannot drift. It is for logs and developers: it is not stable and\n * must not be shown to users or matched on.\n *\n * Every placeholder in a template is a declared param and every declared param is a placeholder,\n * except the few `unrendered` params that carry server text for the app and are kept out of\n * `message` on purpose (pinned by tests/error_catalog.test.ts). Facts that are not placeholders\n * (HTTP status, URL, `uniqueKey`, transaction ids, the raw body, the cause) are typed properties of\n * the error, see {@link GalaErrorContext}.\n */\n\nimport type { GalaErrorPhase } from './error_phases.js';\n\n/**\n * The kinds a param can have: a primitive, or a CLOSED set of string tokens (a readonly tuple).\n * A closed set is a documented union: an app maps each member to its own text and can check that\n * it covered all of them, and a new member is a compile error until it does.\n */\nexport type GalaErrorParamKind = 'string' | 'number' | 'boolean' | readonly string[];\n\n/** One catalog entry (of this catalog, or of a product SDK's own catalog). */\nexport interface GalaErrorCatalogEntry {\n /** The phase this code is thrown in, unless a throw site says otherwise (see {@link GalaErrorPhase}). */\n readonly phase: GalaErrorPhase;\n /** English message template with `{placeholder}` markers. */\n readonly template: string;\n /** Param name to kind. Every param is required and appears in the template, except `unrendered`. */\n readonly params: Readonly<Record<string, GalaErrorParamKind>>;\n /**\n * Params that are carried for the app but deliberately NOT placeholders of the template. Used\n * for `serverMessage` on the codes whose failing answer may be anything (a proxy's page, a\n * validation list): the server's text is data for the app to relay or ignore, and keeping it out\n * of `message` means it cannot reach a log line or a user interface by accident.\n */\n readonly unrendered?: readonly string[];\n}\n\n/**\n * Why a private key was refused (`INVALID_PRIVATE_KEY.params.reason`). A token for the app to map\n * to its own text, never English and never any part of the key.\n *\n * - `wrong_length`: raw bytes that are not 32 bytes long (a `./bridge` Solana secret key: not 64\n * bytes once decoded).\n * - `bad_encoding`: a string that is neither 64 hex characters (optionally `0x`-prefixed, 63 is\n * left-padded) nor a 44-character base64 string (`./bridge`: an Ethereum key that is not `0x`\n * and 64 hex characters; a Solana secret key that is not base58, or whose public half does not\n * match its secret half).\n * - `not_on_curve`: 32 bytes that are not a valid secp256k1 secret scalar.\n * - `no_key_provided`: a lazy key provider returned something that is not a string.\n */\nexport const INVALID_PRIVATE_KEY_REASONS = [\n 'wrong_length',\n 'bad_encoding',\n 'not_on_curve',\n 'no_key_provided',\n] as const;\n\n/** One member of {@link INVALID_PRIVATE_KEY_REASONS}. */\nexport type InvalidPrivateKeyReason = (typeof INVALID_PRIVATE_KEY_REASONS)[number];\n\n/**\n * Why a signer could not produce a signature (`SIGNING_FAILED.params.reason`). A token for the\n * app to map to its own text.\n *\n * - `user_rejected`: the person declined in their wallet (an EIP-1193 `4001`, an ethers\n * `ACTION_REJECTED`, or a wallet that words it \"User rejected/denied ...\"). Nothing is wrong:\n * they may simply try again.\n * - `failed`: anything else the signer threw (a locked wallet, an unreachable extension, a wallet\n * that refused). The original error is `cause`.\n */\nexport const SIGNING_FAILURE_REASONS = ['user_rejected', 'failed'] as const;\n\n/** One member of {@link SIGNING_FAILURE_REASONS}. */\nexport type SigningFailureReason = (typeof SIGNING_FAILURE_REASONS)[number];\n\n/**\n * Why a gateway write refused the token it was asked to move\n * (`INVALID_TOKEN_REFERENCE.params.reason`). A token for the app to map to its own text.\n *\n * - `missing`: neither `tokenClassKey` nor `tokenName` was given.\n * - `ambiguous`: more than one way of naming the token was given (`tokenClassKey` and\n * `tokenName`, or a `tokenName` with an `instance`: a resolved name decides its own instance).\n * - `bad_class_key`: `tokenClassKey` is not a class key: a pipe string needs exactly four\n * non-empty parts, a `$` string at least four (split from the right), an object four non-empty\n * strings. A bare symbol is never a class key and none is derived from it.\n * - `bad_instance`: `instance` is not a string of decimal digits.\n */\nexport const INVALID_TOKEN_REFERENCE_REASONS = [\n 'missing',\n 'ambiguous',\n 'bad_class_key',\n 'bad_instance',\n] as const;\n\n/** One member of {@link INVALID_TOKEN_REFERENCE_REASONS}. */\nexport type InvalidTokenReferenceReason = (typeof INVALID_TOKEN_REFERENCE_REASONS)[number];\n\n/**\n * The `GatewayWrites` options that are refused when missing or of the wrong type\n * (`INVALID_WRITES_OPTION.params.option`). `walletAddress`, `requestTimeoutMs` and\n * `uniqueKeyPrefix` have codes of their own (`INVALID_WALLET_ADDRESS`, `INVALID_TIMEOUT`,\n * `INVALID_UNIQUE_KEY_PREFIX`).\n */\nexport const GATEWAY_WRITES_OPTIONS = [\n 'signer',\n 'gatewayBaseUrl',\n 'httpRequestor',\n 'tokenNameResolver',\n] as const;\n\n/** One member of {@link GATEWAY_WRITES_OPTIONS}. */\nexport type GatewayWritesOption = (typeof GATEWAY_WRITES_OPTIONS)[number];\n\n/**\n * Why the outcome of a gateway write is unknown (`GATEWAY_WRITE_OUTCOME_UNKNOWN.params.reason`).\n * Both say the same thing about the write (it MAY have been applied: never send it again under a\n * fresh key, check `error.uniqueKey` instead) and differ only in what happened to the request.\n *\n * - `timeout`: the POST exceeded `requestTimeoutMs`; the request may still be running.\n * - `transport`: the POST failed before an answer was read (offline, connection reset, DNS, CORS,\n * a body that broke off). The bytes may have reached the gateway.\n */\nexport const GATEWAY_WRITE_OUTCOME_UNKNOWN_REASONS = ['timeout', 'transport'] as const;\n\n/** One member of {@link GATEWAY_WRITE_OUTCOME_UNKNOWN_REASONS}. */\nexport type GatewayWriteOutcomeUnknownReason =\n (typeof GATEWAY_WRITE_OUTCOME_UNKNOWN_REASONS)[number];\n\n/**\n * The `GatewayReads` options that are refused when missing or of the wrong type\n * (`INVALID_READS_OPTION.params.option`). `requestTimeoutMs` has its own code (`INVALID_TIMEOUT`).\n */\nexport const GATEWAY_READS_OPTIONS = ['gatewayBaseUrl', 'httpRequestor'] as const;\n\n/** One member of {@link GATEWAY_READS_OPTIONS}. */\nexport type GatewayReadsOption = (typeof GATEWAY_READS_OPTIONS)[number];\n\n/**\n * The part of a paginated read that was refused (`INVALID_PAGE_REQUEST.params.field`):\n *\n * - `limit` / `pageSize`: results per page, a whole number from 1 to 10 000;\n * - `maxPages`: how many pages a `fetchAll...` read may walk, a whole number from 1 to 10 000;\n * - `bookmark`: the previous page's `nextPageBookmark`, a string.\n */\nexport const PAGE_REQUEST_FIELDS = ['limit', 'pageSize', 'maxPages', 'bookmark'] as const;\n\n/** One member of {@link PAGE_REQUEST_FIELDS}. */\nexport type PageRequestField = (typeof PAGE_REQUEST_FIELDS)[number];\n\n/**\n * Why a wallet provider is not connected (`WALLET_NOT_CONNECTED.params.reason`):\n *\n * - `not_connected`: `connect()` was never called, or `disconnect()` was;\n * - `disconnected`: the wallet reported it is disconnected (EIP-1193 `4900` / `4901`, a\n * `disconnect` event, or an `accountsChanged` with no account);\n * - `unauthorized`: the wallet refused the account (EIP-1193 `4100`): the person has not granted\n * this app access to it.\n */\nexport const WALLET_NOT_CONNECTED_REASONS = [\n 'not_connected',\n 'disconnected',\n 'unauthorized',\n] as const;\n\n/** One member of {@link WALLET_NOT_CONNECTED_REASONS}. */\nexport type WalletNotConnectedReason = (typeof WALLET_NOT_CONNECTED_REASONS)[number];\n\n/**\n * Why connecting a wallet provider failed (`WALLET_CONNECTION_FAILED.params.reason`):\n *\n * - `no_accounts`: the wallet answered `eth_requestAccounts` with no account;\n * - `user_rejected`: the person declined the connection in their wallet (EIP-1193 `4001`);\n * - `failed`: anything else the wallet threw (the original error is `cause`).\n */\nexport const WALLET_CONNECTION_FAILURE_REASONS = [\n 'no_accounts',\n 'user_rejected',\n 'failed',\n] as const;\n\n/** One member of {@link WALLET_CONNECTION_FAILURE_REASONS}. */\nexport type WalletConnectionFailureReason = (typeof WALLET_CONNECTION_FAILURE_REASONS)[number];\n\n/**\n * What a wallet provider was built without (`INVALID_WALLET_PROVIDER_CONFIG.params.missing`):\n *\n * - `eip1193_provider`: an `ExternalWalletProvider` / `GalaWalletProvider` needs the wallet's\n * provider object (`window.ethereum`, an EIP-6963 announcement, `window.gala`);\n * - `private_key_or_eip1193_provider`: `createWalletProvider` needs one of the two.\n */\nexport const WALLET_PROVIDER_CONFIG_MISSING = [\n 'eip1193_provider',\n 'private_key_or_eip1193_provider',\n] as const;\n\n/** One member of {@link WALLET_PROVIDER_CONFIG_MISSING}. */\nexport type WalletProviderConfigMissing = (typeof WALLET_PROVIDER_CONFIG_MISSING)[number];\n\n/**\n * Why `createWallet` refused its input (`INVALID_WALLET_INPUT.params.reason`), never naming any part\n * of it (it may be a key or a mnemonic):\n *\n * - `empty`: nothing but whitespace;\n * - `unrecognized_format`: neither 64 hex digits nor 12 / 24 words of letters;\n * - `unknown_mnemonic_word`: a word that is not in the BIP-39 English wordlist;\n * - `mnemonic_checksum`: every word is known but the phrase's checksum is wrong (a typo or a\n * swapped word).\n */\nexport const WALLET_INPUT_PROBLEMS = [\n 'empty',\n 'unrecognized_format',\n 'unknown_mnemonic_word',\n 'mnemonic_checksum',\n] as const;\n\n/** One member of {@link WALLET_INPUT_PROBLEMS}. */\nexport type WalletInputProblem = (typeof WALLET_INPUT_PROBLEMS)[number];\n\n/** The external networks `./bridge` bridges to and from. */\nexport const BRIDGE_NETWORKS = ['Ethereum', 'Solana'] as const;\n\n/** One member of {@link BRIDGE_NETWORKS}. */\nexport type BridgeNetwork = (typeof BRIDGE_NETWORKS)[number];\n\n/**\n * Why a bridge amount was refused (`INVALID_BRIDGE_AMOUNT.params.reason`):\n *\n * - `not_a_number`: not a finite decimal number;\n * - `not_positive`: zero or negative (a bridge of nothing only wastes the fee);\n * - `too_many_decimals`: more decimal places than the token has (it would be rounded).\n */\nexport const BRIDGE_AMOUNT_PROBLEMS = [\n 'not_a_number',\n 'not_positive',\n 'too_many_decimals',\n] as const;\n\n/** One member of {@link BRIDGE_AMOUNT_PROBLEMS}. */\nexport type BridgeAmountProblem = (typeof BRIDGE_AMOUNT_PROBLEMS)[number];\n\n/**\n * Where a bridge-out failed AFTER GalaConnect accepted its `RequestTokenBridgeOut`\n * (`BRIDGE_OUT_OUTCOME_UNKNOWN.params.step`):\n *\n * - `request_id`: the answer had no bridge request id;\n * - `bridge_token_out`: the `BridgeTokenOut` call failed;\n * - `transaction_hash`: the `BridgeTokenOut` answer had no transaction hash.\n */\nexport const BRIDGE_OUT_STEPS = ['request_id', 'bridge_token_out', 'transaction_hash'] as const;\n\n/** One member of {@link BRIDGE_OUT_STEPS}. */\nexport type BridgeOutStep = (typeof BRIDGE_OUT_STEPS)[number];\n\n/**\n * Where a bridge-in deposit failed once it was being sent (`BRIDGE_DEPOSIT_OUTCOME_UNKNOWN.params.step`):\n *\n * - `send`: sending the deposit transaction failed (it may have reached the network);\n * - `confirmation`: the deposit was sent and its confirmation failed or is unknown;\n * - `registration`: the deposit is confirmed and registering it with GalaConnect failed.\n */\nexport const BRIDGE_DEPOSIT_STEPS = ['send', 'confirmation', 'registration'] as const;\n\n/** One member of {@link BRIDGE_DEPOSIT_STEPS}. */\nexport type BridgeDepositStep = (typeof BRIDGE_DEPOSIT_STEPS)[number];\n\n/**\n * Why a token cannot be wrapped or unwrapped (`TOKEN_NOT_WRAPPABLE.params.reason`):\n *\n * - `not_listed`: the wrappable token list does not have it;\n * - `no_counterpart`: the token it wraps to / unwraps from is not listed;\n * - `unknown_channel`: its channel (or its counterpart's) is not one a wrap moves between.\n */\nexport const WRAP_REFUSAL_REASONS = ['not_listed', 'no_counterpart', 'unknown_channel'] as const;\n\n/** One member of {@link WRAP_REFUSAL_REASONS}. */\nexport type WrapRefusalReason = (typeof WRAP_REFUSAL_REASONS)[number];\n\n/** The two cross-channel directions (`INVALID_WRAP_DIRECTION.params.direction`). */\nexport const WRAP_DIRECTIONS = ['wrap', 'unwrap'] as const;\n\n/** One member of {@link WRAP_DIRECTIONS}. */\nexport type WrapDirection = (typeof WRAP_DIRECTIONS)[number];\n\n/** The whole core catalog. Add a code here before throwing it anywhere in this package. */\nexport const GALA_ERROR_CATALOG = {\n // ---------------------------------------------------------------------------------- transport\n REQUEST_TIMEOUT: {\n phase: 'in_flight',\n template: 'Request to {url} timed out after {timeoutMs} ms.',\n params: { url: 'string', timeoutMs: 'number' },\n },\n TRANSPORT_ERROR: {\n phase: 'in_flight',\n template: 'The request to {url} failed before the server answered.',\n params: { url: 'string' },\n },\n INVALID_TIMEOUT: {\n phase: 'pre_send',\n template:\n '{field} must be a positive number of milliseconds, or Infinity for no timeout (got {value}).',\n params: { field: 'string', value: 'number' },\n },\n\n // ------------------------------------------------------------------------------ wallet / keys\n GALA_WALLET_NOT_AVAILABLE: {\n phase: 'pre_send',\n template: 'Gala wallet is not available. Please ensure the Gala wallet is connected.',\n params: {},\n },\n WALLET_UNAVAILABLE: {\n phase: 'pre_send',\n template: 'No wallet is connected.',\n params: {},\n },\n MALFORMED_WALLET_REQUEST: {\n phase: 'pre_send',\n template: 'Wallet {method} request is malformed.',\n params: { method: 'string' },\n },\n UNSUPPORTED_WALLET_METHOD: {\n phase: 'pre_send',\n template: 'Unsupported wallet method {method}.',\n params: { method: 'string' },\n },\n INVALID_SIGNATURE: {\n phase: 'pre_send',\n template: 'Wallet returned an invalid {scheme} signature.',\n params: { scheme: 'string' },\n },\n INVALID_CHAIN_ID: {\n phase: 'pre_send',\n template: 'Wallet returned an invalid chain id ({chainId}).',\n params: { chainId: 'string' },\n },\n SIGNER_ADDRESS_MISMATCH: {\n phase: 'pre_send',\n template: 'The signing key does not belong to the expected account.',\n params: {},\n },\n INVALID_PRIVATE_KEY: {\n phase: 'pre_send',\n template: 'Invalid private key: {reason}.',\n params: { reason: INVALID_PRIVATE_KEY_REASONS },\n },\n SIGNING_FAILED: {\n phase: 'pre_send',\n template: 'Signing the {method} request failed ({reason}); nothing was sent.',\n params: { method: 'string', reason: SIGNING_FAILURE_REASONS },\n },\n KEY_PROVIDER_FAILED: {\n phase: 'pre_send',\n template: 'The signing key could not be fetched; nothing was sent.',\n params: {},\n },\n INVALID_SIGNING_HASH_LENGTH: {\n phase: 'pre_send',\n template: 'secp256k1 can only sign a 32-byte hash (got {length}).',\n params: { length: 'number' },\n },\n INVALID_WALLET_ADDRESS: {\n phase: 'pre_send',\n template: 'Invalid {field}: \"{value}\" is not an accepted wallet address form.',\n params: { field: 'string', value: 'string' },\n },\n INVALID_ETH_USER_REF_PREFIX: {\n phase: 'pre_send',\n template:\n 'Invalid {field}: \"{value}\" is not a GalaChain user reference. An eth| reference takes the 40 hex digits of the account with no 0x prefix; write it as \"{expected}\".',\n params: { field: 'string', value: 'string', expected: 'string' },\n },\n INVALID_DECIMAL: {\n phase: 'pre_send',\n template: 'Invalid decimal quantity: {value}',\n params: { value: 'string' },\n },\n\n // ------------------------------------------------------------------------- personal-sign DTOs\n PERSONAL_SIGN_NOT_JSON: {\n phase: 'pre_send',\n template: 'Personal-sign DTO is not valid JSON',\n params: {},\n },\n PERSONAL_SIGN_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Personal-sign DTO must be a JSON object',\n params: {},\n },\n PERSONAL_SIGN_BAD_PREFIX: {\n phase: 'pre_send',\n template: 'Personal-sign DTO prefix is not an EIP-191 \"Ethereum Signed Message\" header',\n params: {},\n },\n PERSONAL_SIGN_ENVELOPE_FIELDS: {\n phase: 'pre_send',\n template: 'Personal-sign DTO carries signing-envelope field(s): {fields}',\n params: { fields: 'string' },\n },\n PERSONAL_SIGN_NOT_CANONICAL: {\n phase: 'pre_send',\n template: 'Personal-sign DTO is not in canonical serialized form',\n params: {},\n },\n\n // ------------------------------------------------------------------ EIP-712 payload derivation\n EIP712_NAME_COLLISION: {\n phase: 'pre_send',\n template: 'Name collisions are not supported when deriving EIP-712 types ({name}).',\n params: { name: 'string' },\n },\n EIP712_UNSUPPORTED_VALUE: {\n phase: 'pre_send',\n template: 'Unsupported EIP-712 value of type {valueType}.',\n params: { valueType: 'string' },\n },\n\n // ----------------------------------------------------------------------------- EIP-712 typed data\n TYPED_DATA_NOT_STRING: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be a string',\n params: { what: 'string' },\n },\n TYPED_DATA_UNPAIRED_SURROGATE: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} has an unpaired surrogate',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_HEX_BYTES: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be an even-length 0x hex string',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_SAFE_INTEGER: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be a safe integer',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_INTEGER: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be an integer',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_BOOLEAN: {\n phase: 'pre_send',\n template: 'Invalid typed data: bool must be a boolean',\n params: {},\n },\n TYPED_DATA_BAD_ADDRESS: {\n phase: 'pre_send',\n template: 'Invalid typed data: address must be 0x followed by 40 hex digits',\n params: {},\n },\n TYPED_DATA_BAD_CHECKSUM: {\n phase: 'pre_send',\n template: 'Invalid typed data: address has a bad checksum',\n params: {},\n },\n TYPED_DATA_BYTES_LENGTH: {\n phase: 'pre_send',\n template: 'Invalid typed data: {type} must be exactly {width} bytes',\n params: { type: 'string', width: 'number' },\n },\n TYPED_DATA_OUT_OF_BOUNDS: {\n phase: 'pre_send',\n template: 'Invalid typed data: value out of bounds for {type}',\n params: { type: 'string' },\n },\n TYPED_DATA_UNSUPPORTED_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: unsupported type \"{type}\"',\n params: { type: 'string' },\n },\n TYPED_DATA_FIELDS_NOT_LIST: {\n phase: 'pre_send',\n template: 'Invalid typed data: type {typeName} must be a list of fields',\n params: { typeName: 'string' },\n },\n TYPED_DATA_FIELD_MALFORMED: {\n phase: 'pre_send',\n template: 'Invalid typed data: type {typeName} has a field without a string name and type',\n params: { typeName: 'string' },\n },\n TYPED_DATA_INVALID_FIELD_NAME: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid field name \"{name}\"',\n params: { name: 'string' },\n },\n TYPED_DATA_DUPLICATE_FIELD: {\n phase: 'pre_send',\n template: 'Invalid typed data: duplicate field \"{name}\" in {typeName}',\n params: { name: 'string', typeName: 'string' },\n },\n TYPED_DATA_INVALID_TYPE_NAME: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid type name \"{name}\"',\n params: { name: 'string' },\n },\n TYPED_DATA_CIRCULAR_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: circular type reference in {typeName}',\n params: { typeName: 'string' },\n },\n TYPED_DATA_UNKNOWN_FIELD_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: unknown type \"{type}\" in {typeName}',\n params: { type: 'string', typeName: 'string' },\n },\n TYPED_DATA_NO_PRIMARY_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: missing primary type',\n params: {},\n },\n TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: ambiguous primary types or unused types ({roots})',\n params: { roots: 'string' },\n },\n TYPED_DATA_ARRAY_EXPECTED: {\n phase: 'pre_send',\n template: 'Invalid typed data: {type} array value must be an array',\n params: { type: 'string' },\n },\n TYPED_DATA_ARRAY_LENGTH_MISMATCH: {\n phase: 'pre_send',\n template: 'Invalid typed data: array length mismatch',\n params: {},\n },\n TYPED_DATA_STRUCT_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Invalid typed data: {typeName} value must be an object',\n params: { typeName: 'string' },\n },\n TYPED_DATA_MISSING_FIELD: {\n phase: 'pre_send',\n template: 'Invalid typed data: {typeName} value is missing field \"{field}\"',\n params: { typeName: 'string', field: 'string' },\n },\n TYPED_DATA_DOMAIN_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Invalid typed data: domain must be an object',\n params: {},\n },\n TYPED_DATA_INVALID_DOMAIN_KEY: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid typed-data domain key {key}',\n params: { key: 'string' },\n },\n\n // ---------------------------------------------------------------------------------- unique keys\n INVALID_UNIQUE_KEY: {\n phase: 'pre_send',\n template:\n 'The uniqueKey \"{uniqueKey}\" must be 1-128 characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".',\n params: { uniqueKey: 'string' },\n },\n INVALID_UNIQUE_KEY_PREFIX: {\n phase: 'pre_send',\n template:\n 'uniqueKeyPrefix \"{uniqueKeyPrefix}\" must be at most {maxLength} characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".',\n params: { uniqueKeyPrefix: 'string', maxLength: 'number' },\n },\n CSPRNG_UNAVAILABLE: {\n phase: 'pre_send',\n template:\n 'No cryptographically secure random source (globalThis.crypto.getRandomValues) is available to mint a uniqueKey or a new wallet; install a getRandomValues polyfill (react-native-get-random-values on Hermes).',\n params: {},\n },\n\n // ----------------------------------------------------------------------------- gateway writes\n INVALID_WRITES_OPTION: {\n phase: 'pre_send',\n template: 'GatewayWrites option {option} is missing or is not of the expected type.',\n params: { option: GATEWAY_WRITES_OPTIONS },\n },\n INVALID_QUANTITY: {\n phase: 'pre_send',\n template:\n '{field} must be a positive decimal number of whole tokens, written as a string (got \"{value}\").',\n params: { field: 'string', value: 'string' },\n },\n INVALID_TOKEN_REFERENCE: {\n phase: 'pre_send',\n template: 'Invalid token reference {field}: {reason}.',\n params: { field: 'string', reason: INVALID_TOKEN_REFERENCE_REASONS },\n },\n INVALID_TOKEN_BATCH: {\n phase: 'pre_send',\n template: '{method} takes 1 to {max} tokens (got {count}).',\n params: { method: 'string', count: 'number', max: 'number' },\n },\n INVALID_LOCK_EXPIRES: {\n phase: 'pre_send',\n template:\n 'expires must be a non-negative whole number of epoch milliseconds, 0 for none (got {value}).',\n params: { value: 'string' },\n },\n INVALID_LOCK_NAME: {\n phase: 'pre_send',\n template: 'The lock name must be a string (got a {valueType}).',\n params: { valueType: 'string' },\n },\n NO_TOKEN_NAME_RESOLVER: {\n phase: 'pre_send',\n template:\n 'The token name \"{tokenName}\" cannot be resolved: no tokenNameResolver is configured. Pass its tokenClassKey instead.',\n params: { tokenName: 'string' },\n },\n TOKEN_NAME_RESOLUTION_FAILED: {\n phase: 'pre_send',\n template:\n 'The token name \"{tokenName}\" could not be resolved to a token class key; nothing was sent.',\n params: { tokenName: 'string' },\n },\n GATEWAY_WRITE_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'The outcome of {method} is unknown ({reason}): the request may have reached the gateway. Check the write by its uniqueKey before sending it again.',\n params: { method: 'string', reason: GATEWAY_WRITE_OUTCOME_UNKNOWN_REASONS },\n },\n GATEWAY_HTTP_ERROR: {\n phase: 'post_send',\n template: 'The gateway answered {method} with HTTP {status}.',\n params: { method: 'string', status: 'number', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n GATEWAY_WRITE_REJECTED: {\n phase: 'post_send',\n template: 'GalaChain rejected {method} (Status {chainStatus}, error key \"{errorKey}\").',\n params: {\n method: 'string',\n chainStatus: 'number',\n errorKey: 'string',\n serverMessage: 'string',\n },\n unrendered: ['serverMessage'],\n },\n GATEWAY_RESPONSE_INVALID: {\n phase: 'post_send',\n template:\n 'The gateway answered {method} with something that is not a GalaChain result; the write may have been applied.',\n params: { method: 'string' },\n },\n\n // ------------------------------------------------------------------------------ gateway reads\n INVALID_READS_OPTION: {\n phase: 'pre_send',\n template: 'GatewayReads option {option} is missing or is not of the expected type.',\n params: { option: GATEWAY_READS_OPTIONS },\n },\n INVALID_PAGE_REQUEST: {\n phase: 'pre_send',\n template:\n '{field} is not valid for a paginated read (got {value}): a page size or page count is a whole number from 1 to 10000, a bookmark a string.',\n params: { field: PAGE_REQUEST_FIELDS, value: 'string' },\n },\n GATEWAY_READ_REJECTED: {\n phase: 'post_send',\n template: 'GalaChain refused {method} (Status {chainStatus}, error key \"{errorKey}\").',\n params: {\n method: 'string',\n chainStatus: 'number',\n errorKey: 'string',\n serverMessage: 'string',\n },\n unrendered: ['serverMessage'],\n },\n GATEWAY_READ_RESPONSE_INVALID: {\n phase: 'post_send',\n template: 'The gateway answered {method} with something that is not a usable GalaChain result.',\n params: { method: 'string' },\n },\n TOKEN_CLASS_NOT_FOUND: {\n phase: 'post_send',\n template: 'GalaChain has no token class {tokenClassKey}.',\n params: { tokenClassKey: 'string' },\n },\n PAGINATION_LIMIT_EXCEEDED: {\n phase: 'post_send',\n template:\n 'Reading every page of {method} takes more than {maxPages} pages; narrow the filter or raise maxPages.',\n params: { method: 'string', maxPages: 'number' },\n },\n\n // ------------------------------------------------------------- wallet providers (`./providers`)\n WALLET_NOT_CONNECTED: {\n phase: 'pre_send',\n template: 'The wallet is not connected ({reason}): connect it before {operation}.',\n params: { reason: WALLET_NOT_CONNECTED_REASONS, operation: 'string' },\n },\n WALLET_CONNECTION_FAILED: {\n phase: 'pre_send',\n template: 'Connecting to the wallet failed ({reason}).',\n params: { reason: WALLET_CONNECTION_FAILURE_REASONS },\n },\n INVALID_WALLET_PROVIDER_CONFIG: {\n phase: 'pre_send',\n template: 'A wallet provider cannot be built without {missing}.',\n params: { missing: WALLET_PROVIDER_CONFIG_MISSING },\n },\n PRIVATE_KEY_NOT_ACCESSIBLE: {\n phase: 'pre_send',\n template:\n 'This wallet provider signs in the wallet and cannot give out a private key; only a PrivateKeyProvider holds one.',\n params: {},\n },\n\n // ----------------------------------------------------------------------------- wallet helpers\n INVALID_WALLET_INPUT: {\n phase: 'pre_send',\n template:\n 'The wallet input was refused ({reason}): give a private key (64 hex digits) or a 12- or 24-word mnemonic.',\n params: { reason: WALLET_INPUT_PROBLEMS },\n },\n\n // ------------------------------------------------------------------------ bridge (`./bridge`)\n INVALID_BRIDGE_AMOUNT: {\n phase: 'pre_send',\n template: 'The bridge amount \"{value}\" was refused ({reason}).',\n params: { value: 'string', reason: BRIDGE_AMOUNT_PROBLEMS },\n },\n UNSUPPORTED_BRIDGE_TOKEN: {\n phase: 'pre_send',\n template: '{symbol} cannot be bridged with {network}.',\n params: { network: 'string', symbol: 'string' },\n },\n BRIDGE_NOT_CONFIGURED: {\n phase: 'pre_send',\n template:\n '{network} bridging is not configured: give the bridge a {network} private key (ethereumPrivateKey / solanaPrivateKey).',\n params: { network: BRIDGE_NETWORKS },\n },\n INVALID_TRANSACTION_HASH: {\n phase: 'pre_send',\n template: '\"{value}\" is not a {network} transaction hash.',\n params: { network: BRIDGE_NETWORKS, value: 'string' },\n },\n INVALID_BRIDGE_OPTION: {\n phase: 'pre_send',\n template: 'The bridge option {option} is missing or out of range.',\n params: { option: 'string' },\n },\n BRIDGE_RESPONSE_INVALID: {\n phase: 'post_send',\n template:\n 'GalaConnect answered {method} without a usable {missing}; the request may have been accepted.',\n params: { method: 'string', missing: 'string' },\n },\n BRIDGE_READ_RESPONSE_INVALID: {\n phase: 'post_send',\n template: 'GalaConnect answered {method} with something that is not a usable result.',\n params: { method: 'string' },\n },\n BRIDGE_WRITE_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'The outcome of {method} is unknown: the request failed in transit and may have reached GalaConnect. Check it before sending it again.',\n params: { method: 'string' },\n },\n GALACONNECT_HTTP_ERROR: {\n phase: 'post_send',\n template: 'GalaConnect answered {method} with HTTP {status}.',\n params: { method: 'string', status: 'number', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n BRIDGE_TOKEN_NOT_FOUND: {\n phase: 'post_send',\n template: 'GalaConnect has no verified bridge configuration for {symbol}.',\n params: { symbol: 'string' },\n },\n TOKEN_NOT_WRAPPABLE: {\n phase: 'post_send',\n template: '{tokenId} cannot be wrapped or unwrapped ({reason}).',\n params: { tokenId: 'string', reason: WRAP_REFUSAL_REASONS },\n },\n INVALID_WRAP_DIRECTION: {\n phase: 'pre_send',\n template:\n 'Cannot {direction} {symbol}: it is on the wrong channel for it (use the other direction).',\n params: { symbol: 'string', direction: WRAP_DIRECTIONS },\n },\n BRIDGE_REQUEST_REJECTED: {\n phase: 'post_send',\n template: 'GalaChain refused {method} (Status {chainStatus}, error key \"{errorKey}\").',\n params: {\n method: 'string',\n chainStatus: 'number',\n errorKey: 'string',\n serverMessage: 'string',\n },\n unrendered: ['serverMessage'],\n },\n BRIDGE_OUT_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'GalaConnect accepted the bridge-out request, which may have locked the tokens, then the bridge-out failed at {step}. Check it before bridging again.',\n params: { step: BRIDGE_OUT_STEPS, bridgeRequestId: 'string' },\n unrendered: ['bridgeRequestId'],\n },\n BRIDGE_DEPOSIT_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'The {network} bridge deposit may have been sent, then its {step} failed. Check the deposit before sending another.',\n params: { network: BRIDGE_NETWORKS, step: BRIDGE_DEPOSIT_STEPS, transactionHash: 'string' },\n unrendered: ['transactionHash'],\n },\n BRIDGE_CHAIN_READ_FAILED: {\n phase: 'post_send',\n template: 'The {network} read {call} failed or answered something unusable; nothing was sent.',\n params: { network: BRIDGE_NETWORKS, call: 'string' },\n },\n INSUFFICIENT_BRIDGE_BALANCE: {\n phase: 'pre_send',\n template: 'The {network} balance of {symbol} is {available}; the bridge needs {needed}.',\n params: { network: BRIDGE_NETWORKS, symbol: 'string', needed: 'string', available: 'string' },\n },\n BRIDGE_STATUS_TIMEOUT: {\n phase: 'in_flight',\n template:\n 'The bridge transaction did not reach a final status within {timeoutMs} ms (last status {lastStatus}); it may still complete.',\n params: { transactionHash: 'string', timeoutMs: 'number', lastStatus: 'number' },\n unrendered: ['transactionHash'],\n },\n\n // ------------------------------------------------------------------- React context (`./react`)\n WALLET_CONTEXT_MISSING: {\n phase: 'pre_send',\n template: 'The wallet hooks and the wallet context need a WalletProvider above them.',\n params: {},\n },\n} as const satisfies Record<string, GalaErrorCatalogEntry>;\n\n/** Every error code the core SDK can throw. */\nexport type GalaErrorCode = keyof typeof GALA_ERROR_CATALOG;\n\ninterface KindToType {\n string: string;\n number: number;\n boolean: boolean;\n}\n\n/** The value type of a param kind: a primitive, or the union of a closed set's members. */\ntype ParamValue<K> = K extends readonly (infer Member)[]\n ? Member\n : K extends keyof KindToType\n ? KindToType[K]\n : never;\n\n/**\n * The named params of code `C` of ANY catalog object (`typeof SOME_CATALOG`): a flat object of\n * primitives (or closed string tokens). A product SDK derives its own params type from its\n * catalog with it, so every catalog types its params the same way.\n */\nexport type ErrorParamsOf<\n Catalog extends Readonly<Record<string, GalaErrorCatalogEntry>>,\n C extends keyof Catalog,\n> = {\n readonly [P in keyof Catalog[C]['params']]: ParamValue<Catalog[C]['params'][P]>;\n};\n\n/** The named params of one core error code. */\nexport type GalaErrorParams<C extends GalaErrorCode> = ErrorParamsOf<typeof GALA_ERROR_CATALOG, C>;\n\n/**\n * The English template of every core error code, `{placeholder}` markers included. An optional\n * seed or fallback for an app's own translations; the SDK's `message` is generated from it. A\n * product SDK exports the templates of its own codes next to it.\n */\nexport const galaErrorTemplates: { readonly [C in GalaErrorCode]: string } = Object.fromEntries(\n Object.entries(GALA_ERROR_CATALOG).map(([code, entry]) => [code, entry.template]),\n) as { readonly [C in GalaErrorCode]: string };\n\nconst PLACEHOLDER = /\\{([A-Za-z0-9_]+)\\}/gu;\n\n/** Fills a template's `{placeholders}` from `params`; an unknown placeholder is left as written. */\nexport function renderGalaErrorTemplate(\n template: string,\n params: Readonly<Record<string, unknown>>,\n): string {\n return template.replace(PLACEHOLDER, (whole, name: string) => {\n const value = params[name];\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : whole;\n });\n}\n\n/** The placeholder names a template uses, in order of first appearance. */\nexport function templatePlaceholders(template: string): string[] {\n return [...new Set([...template.matchAll(PLACEHOLDER)].map((match) => match[1] as string))];\n}\n","import type { GALA_ERROR_CATALOG, GalaErrorCode } from './error_catalog.js';\n\n/**\n * The phase of every core catalog code, WITHOUT the catalog. A failure guard (a product SDK's\n * `classifyFailure`, `mayHaveBeenQueued`, ...) needs only a code's phase, and the catalog's English\n * templates are several kB: reading the phase from here keeps an app shell that imports a guard\n * from loading them. The catalog entry is still where a code is declared; this table is checked\n * against it AT COMPILE TIME, in both directions (a missing code, an extra code or a different\n * phase is a type error), so the two cannot drift. A product SDK keeps the same kind of table for\n * its own codes.\n */\nexport const GALA_ERROR_PHASE_BY_CODE = {\n REQUEST_TIMEOUT: 'in_flight',\n TRANSPORT_ERROR: 'in_flight',\n INVALID_TIMEOUT: 'pre_send',\n GALA_WALLET_NOT_AVAILABLE: 'pre_send',\n WALLET_UNAVAILABLE: 'pre_send',\n MALFORMED_WALLET_REQUEST: 'pre_send',\n UNSUPPORTED_WALLET_METHOD: 'pre_send',\n INVALID_SIGNATURE: 'pre_send',\n INVALID_CHAIN_ID: 'pre_send',\n SIGNER_ADDRESS_MISMATCH: 'pre_send',\n INVALID_PRIVATE_KEY: 'pre_send',\n SIGNING_FAILED: 'pre_send',\n KEY_PROVIDER_FAILED: 'pre_send',\n INVALID_SIGNING_HASH_LENGTH: 'pre_send',\n INVALID_WALLET_ADDRESS: 'pre_send',\n INVALID_ETH_USER_REF_PREFIX: 'pre_send',\n INVALID_DECIMAL: 'pre_send',\n PERSONAL_SIGN_NOT_JSON: 'pre_send',\n PERSONAL_SIGN_NOT_OBJECT: 'pre_send',\n PERSONAL_SIGN_BAD_PREFIX: 'pre_send',\n PERSONAL_SIGN_ENVELOPE_FIELDS: 'pre_send',\n PERSONAL_SIGN_NOT_CANONICAL: 'pre_send',\n EIP712_NAME_COLLISION: 'pre_send',\n EIP712_UNSUPPORTED_VALUE: 'pre_send',\n TYPED_DATA_NOT_STRING: 'pre_send',\n TYPED_DATA_UNPAIRED_SURROGATE: 'pre_send',\n TYPED_DATA_NOT_HEX_BYTES: 'pre_send',\n TYPED_DATA_NOT_SAFE_INTEGER: 'pre_send',\n TYPED_DATA_NOT_INTEGER: 'pre_send',\n TYPED_DATA_NOT_BOOLEAN: 'pre_send',\n TYPED_DATA_BAD_ADDRESS: 'pre_send',\n TYPED_DATA_BAD_CHECKSUM: 'pre_send',\n TYPED_DATA_BYTES_LENGTH: 'pre_send',\n TYPED_DATA_OUT_OF_BOUNDS: 'pre_send',\n TYPED_DATA_UNSUPPORTED_TYPE: 'pre_send',\n TYPED_DATA_FIELDS_NOT_LIST: 'pre_send',\n TYPED_DATA_FIELD_MALFORMED: 'pre_send',\n TYPED_DATA_INVALID_FIELD_NAME: 'pre_send',\n TYPED_DATA_DUPLICATE_FIELD: 'pre_send',\n TYPED_DATA_INVALID_TYPE_NAME: 'pre_send',\n TYPED_DATA_CIRCULAR_TYPE: 'pre_send',\n TYPED_DATA_UNKNOWN_FIELD_TYPE: 'pre_send',\n TYPED_DATA_NO_PRIMARY_TYPE: 'pre_send',\n TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE: 'pre_send',\n TYPED_DATA_ARRAY_EXPECTED: 'pre_send',\n TYPED_DATA_ARRAY_LENGTH_MISMATCH: 'pre_send',\n TYPED_DATA_STRUCT_NOT_OBJECT: 'pre_send',\n TYPED_DATA_MISSING_FIELD: 'pre_send',\n TYPED_DATA_DOMAIN_NOT_OBJECT: 'pre_send',\n TYPED_DATA_INVALID_DOMAIN_KEY: 'pre_send',\n INVALID_UNIQUE_KEY: 'pre_send',\n INVALID_UNIQUE_KEY_PREFIX: 'pre_send',\n CSPRNG_UNAVAILABLE: 'pre_send',\n INVALID_WRITES_OPTION: 'pre_send',\n INVALID_QUANTITY: 'pre_send',\n INVALID_TOKEN_REFERENCE: 'pre_send',\n INVALID_TOKEN_BATCH: 'pre_send',\n INVALID_LOCK_EXPIRES: 'pre_send',\n INVALID_LOCK_NAME: 'pre_send',\n NO_TOKEN_NAME_RESOLVER: 'pre_send',\n TOKEN_NAME_RESOLUTION_FAILED: 'pre_send',\n GATEWAY_WRITE_OUTCOME_UNKNOWN: 'in_flight',\n GATEWAY_HTTP_ERROR: 'post_send',\n GATEWAY_WRITE_REJECTED: 'post_send',\n GATEWAY_RESPONSE_INVALID: 'post_send',\n INVALID_READS_OPTION: 'pre_send',\n INVALID_PAGE_REQUEST: 'pre_send',\n GATEWAY_READ_REJECTED: 'post_send',\n GATEWAY_READ_RESPONSE_INVALID: 'post_send',\n TOKEN_CLASS_NOT_FOUND: 'post_send',\n PAGINATION_LIMIT_EXCEEDED: 'post_send',\n WALLET_NOT_CONNECTED: 'pre_send',\n WALLET_CONNECTION_FAILED: 'pre_send',\n INVALID_WALLET_PROVIDER_CONFIG: 'pre_send',\n PRIVATE_KEY_NOT_ACCESSIBLE: 'pre_send',\n INVALID_WALLET_INPUT: 'pre_send',\n INVALID_BRIDGE_AMOUNT: 'pre_send',\n UNSUPPORTED_BRIDGE_TOKEN: 'pre_send',\n BRIDGE_NOT_CONFIGURED: 'pre_send',\n INVALID_TRANSACTION_HASH: 'pre_send',\n INVALID_BRIDGE_OPTION: 'pre_send',\n BRIDGE_RESPONSE_INVALID: 'post_send',\n BRIDGE_READ_RESPONSE_INVALID: 'post_send',\n BRIDGE_WRITE_OUTCOME_UNKNOWN: 'in_flight',\n GALACONNECT_HTTP_ERROR: 'post_send',\n BRIDGE_TOKEN_NOT_FOUND: 'post_send',\n TOKEN_NOT_WRAPPABLE: 'post_send',\n INVALID_WRAP_DIRECTION: 'pre_send',\n BRIDGE_REQUEST_REJECTED: 'post_send',\n BRIDGE_OUT_OUTCOME_UNKNOWN: 'in_flight',\n BRIDGE_DEPOSIT_OUTCOME_UNKNOWN: 'in_flight',\n BRIDGE_CHAIN_READ_FAILED: 'post_send',\n INSUFFICIENT_BRIDGE_BALANCE: 'pre_send',\n BRIDGE_STATUS_TIMEOUT: 'in_flight',\n WALLET_CONTEXT_MISSING: 'pre_send',\n} as const satisfies {\n readonly [C in GalaErrorCode]: (typeof GALA_ERROR_CATALOG)[C]['phase'];\n};\n\n/** True for a code the CORE catalog defines (a product SDK's own codes are not). */\nexport function isGalaCatalogCode(code: string): code is GalaErrorCode {\n return Object.hasOwn(GALA_ERROR_PHASE_BY_CODE, code);\n}\n","/**\n * How far an operation had got when it failed, measured against the request it exists to send:\n * for a write, the POST that carries the signed DTO to the gateway; for a read, the GET.\n *\n * - `pre_send`: NOTHING was transmitted. Everything up to the request (validation, symbol\n * resolution, the signer, the wallet, a key provider) ran and failed, so no write can have been\n * queued. A write that failed `pre_send` is never \"maybe applied\".\n * - `in_flight`: the request left (or may have left) and no answer was read: a timeout, a broken\n * connection, a stream that dropped. For a write the outcome is unknown.\n * - `post_send`: an answer was read, or the write was already accepted: a refusal, an\n * acknowledgement that proves nothing, an unusable body, and every failure of a confirmation.\n *\n * Each catalog entry (core's and every product SDK's) declares the phase its code is thrown in; a\n * throw site where the same code can occur in another phase overrides it\n * (`GalaErrorContext.phase`). It is a typed property of every `GalaSDKError` (`error.phase`).\n *\n * This module has no imports, on purpose: it is the closed set of phases, shared by the catalogs,\n * the light phase tables (`error_phase_table.ts`) and the failure view.\n */\nexport const GALA_ERROR_PHASES = ['pre_send', 'in_flight', 'post_send'] as const;\n\n/** One member of {@link GALA_ERROR_PHASES}. */\nexport type GalaErrorPhase = (typeof GALA_ERROR_PHASES)[number];\n","/**\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","import { GALA_ERROR_BRAND } from '../utils/error_brand.js';\nimport {\n GALA_ERROR_CATALOG,\n renderGalaErrorTemplate,\n type GalaErrorCatalogEntry,\n type GalaErrorCode,\n type GalaErrorParams,\n} from './error_catalog.js';\nimport type { GalaErrorPhase } from './error_phases.js';\n\n/**\n * The facts of an error that are not placeholders of its message: where it happened and what the\n * server said. All optional; none is localized text.\n */\nexport interface GalaErrorContext {\n /** The HTTP status of the response that caused the error. */\n status?: number | undefined;\n /**\n * The response body: parsed JSON when the failing response had it, else the raw text (which\n * the error then exposes as {@link GalaSDKError.bodyText}).\n */\n body?: unknown;\n /** The URL the failing request went to. */\n url?: string | undefined;\n /** The `uniqueKey` of the write this error is about: the handle for `confirm()` and recovery. */\n uniqueKey?: string | undefined;\n /** The transaction id of the queued request, `null` when unknown. */\n requestTransactionId?: string | null | undefined;\n /** The transaction id of the apply, `null` when unknown. */\n applyTransactionId?: string | null | undefined;\n /** The block the apply landed in, `null` when unknown. */\n blockNumber?: number | null | undefined;\n /** How long to wait before retrying, from the server's `Retry-After`. */\n retryAfterMs?: number | undefined;\n /** The error that caused this one (a transport failure, a wallet rejection). */\n cause?: unknown;\n /**\n * The phase of THIS occurrence when it differs from the code's catalog phase (see\n * {@link GalaErrorPhase}): for example a product code that is `pre_send` from a local registry\n * but `post_send` when it is derived from a server answer.\n */\n phase?: GalaErrorPhase | undefined;\n /** True when the failing operation was on the shadow (dark) path; see {@link GalaSDKError.shadow}. */\n shadow?: boolean | undefined;\n /**\n * `false` for the failure of a READ (see {@link GalaSDKError.write}); anything else, including\n * absent, is a write (fail-closed). Ignored when `uniqueKey` is set: that is a write.\n */\n write?: boolean | undefined;\n /** The wallet's own code on the error a signer threw; see {@link GalaSDKError.walletCode}. */\n walletCode?: number | string | undefined;\n}\n\n/** What the params of ANY SDK error are: a flat object of primitives. */\nexport type GalaErrorParamsShape = Readonly<Record<string, string | number | boolean>>;\n\n/**\n * The params type of a CORE code, and `never` for any other string: constructing a `GalaSDKError`\n * itself with a code the core catalog does not define is a compile error. A product SDK's subclass\n * supplies its own params type for its codes.\n */\nexport type GalaParamsOf<C extends string> = C extends GalaErrorCode ? GalaErrorParams<C> : never;\n\n/** Reads the catalog entry of `code`, failing loudly for a code the catalog does not define. */\nfunction catalogEntry(\n catalog: Readonly<Record<string, GalaErrorCatalogEntry>>,\n code: string,\n): GalaErrorCatalogEntry {\n const entry = Object.hasOwn(catalog, code) ? catalog[code] : undefined;\n if (entry === undefined) {\n // Unreachable through the types (the code parameter is the catalog's own key union); a cast\n // that smuggles in a foreign code is a programming error, so it fails at the throw site.\n throw new TypeError(`${code} is not a code of this error class's catalog`);\n }\n return entry;\n}\n\n/**\n * Error raised by the SDKs for validation, signing, transport, gateway, chain, or transaction\n * failures. Every product SDK's error class (`GSwapSDKError`, ...) extends it, so\n * `error instanceof GalaSDKError` (or {@link isGalaError}) recognises an error from ANY of them.\n *\n * Branch on {@link code} (stable) and render {@link params} through your own localization.\n * {@link message} is English generated from the catalog template for logs and developers: it\n * is not stable and must never be shown to a user or matched on.\n *\n * The class reads a code's template and phase from its static {@link GalaSDKError.catalog}: the\n * core catalog here, core's plus a product's own codes on a product subclass. One code is defined\n * in exactly one catalog.\n */\nexport class GalaSDKError<C extends string = GalaErrorCode, P = GalaParamsOf<C>> extends Error {\n /**\n * The catalog this class reads templates and phases from. A product SDK's subclass overrides it\n * with an object holding core's codes AND its own (core's entries are never redefined there).\n */\n public static readonly catalog: Readonly<Record<string, GalaErrorCatalogEntry>> =\n GALA_ERROR_CATALOG;\n\n /** The stable, machine-readable code. */\n public readonly code: C;\n /** The named placeholders of the error: a flat object of primitives, safe to localize with. */\n public readonly params: P;\n /** The server's `Retry-After` in milliseconds (a rate-limited answer), when it sent one. */\n public readonly retryAfterMs: number | undefined;\n /** The HTTP status of the response that caused this error, when there was one. */\n public readonly status: number | undefined;\n /**\n * The response body parsed as JSON, when the failing response had one; `undefined` for a body\n * that was not JSON (see {@link bodyText}). Never part of {@link message}.\n */\n public readonly body: unknown;\n /**\n * The raw text of a failing response whose body was NOT JSON (a proxy's HTML 502, a WAF page,\n * an empty body). It is kept here for diagnostics and is never copied into {@link message},\n * so it cannot reach a user interface by accident.\n */\n public readonly bodyText: string | undefined;\n /** The URL the failing request went to, when there was one. */\n public readonly url: string | undefined;\n /** The `uniqueKey` of the write this error is about, when there is one. */\n public readonly uniqueKey: string | undefined;\n /** The transaction id of the queued request, when known. */\n public readonly requestTransactionId: string | null | undefined;\n /** The transaction id of the apply, when known. */\n public readonly applyTransactionId: string | null | undefined;\n /** The block the apply landed in, when known. */\n public readonly blockNumber: number | null | undefined;\n /**\n * How far the operation had got when this was thrown, against the request it exists to send\n * (see {@link GalaErrorPhase}): `pre_send` means NOTHING was transmitted, so a write that\n * failed this way cannot have been queued; `in_flight` means the request left and no answer was\n * read; `post_send` means an answer was read or the write was already accepted. Every catalog\n * code declares its phase, and a throw site can refine it. A product SDK's failure classifier\n * (gswap-sdk's `classifyFailure`, `isPreSendError`) folds it into its answers.\n */\n public readonly phase: GalaErrorPhase;\n /**\n * True when this error came from the shadow (dark) path of a product SDK (gswap-sdk's\n * `swapShadow`, `submitSwapShadow`, `ChainGateway.submitShadow`), whatever failed there. The\n * classification is the same as on the public path; this is how an app applies its own\n * dark-swap policy.\n */\n public readonly shadow: boolean;\n /**\n * Whether this failure is a WRITE's, as the guards read it: `false` only for the failure of a\n * READ (a quote, a list, a result read), which has no `uniqueKey` to confirm and nothing\n * pending, so a 5xx there is `transient` and retryable. It is `true` for everything else, and\n * always when {@link uniqueKey} is set. That is fail-closed: a failure that does not say it is a\n * read is judged a write, where a 5xx is `unknown` and never retried. Apps that carry an error\n * through their own wrapper copy this field next to `uniqueKey` (`FailureView.write`).\n */\n public readonly write: boolean;\n /**\n * On `SIGNING_FAILED`: the code the wallet put on the error its signer threw, when it set one: an\n * EIP-1193 / JSON-RPC number such as `4001` (the person declined) or `-32603`, or an ethers /\n * viem string such as `'ACTION_REJECTED'`. It is read from the `cause`'s own `code` and is\n * always a short primitive; `undefined` when the wallet sent none, and on every other code. It is\n * a typed field, not a param: it is data for an app's analytics or its own wallet-specific\n * wording, never part of `message`, and `params.reason` stays the stable thing to branch on.\n */\n public readonly walletCode: number | string | undefined;\n\n constructor(code: C, params: NoInfer<P>, context: GalaErrorContext = {}) {\n const entry = catalogEntry(new.target.catalog, code);\n super(\n renderGalaErrorTemplate(entry.template, params as Readonly<Record<string, unknown>>),\n context.cause === undefined ? undefined : { cause: context.cause },\n );\n this.name = 'GalaSDKError';\n this.code = code;\n this.params = params;\n this.retryAfterMs = context.retryAfterMs;\n this.status = context.status;\n this.body = typeof context.body === 'string' ? undefined : context.body;\n this.bodyText = typeof context.body === 'string' ? context.body : undefined;\n this.url = context.url;\n this.uniqueKey = context.uniqueKey;\n this.requestTransactionId = context.requestTransactionId;\n this.applyTransactionId = context.applyTransactionId;\n this.blockNumber = context.blockNumber;\n this.phase = context.phase ?? entry.phase;\n this.shadow = context.shadow ?? false;\n this.write =\n context.uniqueKey !== undefined && context.uniqueKey !== '' ? true : context.write !== false;\n this.walletCode = context.walletCode;\n }\n\n /**\n * The SDK error brand (`Symbol.for('@gala-chain/gala-core-sdk/error')`), always `true`, carried\n * by every product SDK's error class through inheritance. The dependency-free helpers\n * (`isWalletUserRejection`, `isGalaErrorLike`) recognise an SDK error by it instead of\n * `instanceof`, so they work across copies of the SDK and without importing this class. It lives\n * on the prototype: it is not an own property and is never copied or logged.\n */\n public get [GALA_ERROR_BRAND](): true {\n return true;\n }\n\n /**\n * True when the failure means \"that thing does not exist\" rather than \"something went wrong\":\n * an HTTP 404. A product SDK's subclass adds its own not-found codes (gswap-sdk: no pool, an\n * unknown token).\n */\n public get notFound(): boolean {\n return this.status === 404;\n }\n}\n\n/** Any thrown value that is a CORE SDK error, narrowed to the union of every core code. */\nexport type AnyGalaError = { [C in GalaErrorCode]: GalaSDKError<C> }[GalaErrorCode];\n\n/**\n * True when `value` is an SDK error (core's, or any product SDK's subclass) and, when `code` is\n * given, carries exactly that core code. With a code, `error.params` narrows to that code's\n * params. Without one it narrows only to \"an SDK error with some string code\": a product error's\n * code is not a core code, so it is not typed as one.\n *\n * @example\n * ```ts\n * if (isGalaError(error, 'INVALID_PRIVATE_KEY')) {\n * t(`errors.key.${error.params.reason}`);\n * }\n * ```\n */\nexport function isGalaError(value: unknown): value is GalaSDKError<string, GalaErrorParamsShape>;\nexport function isGalaError<C extends GalaErrorCode>(\n value: unknown,\n code: C,\n): value is GalaSDKError<C>;\nexport function isGalaError(value: unknown, code?: GalaErrorCode): boolean {\n return value instanceof GalaSDKError && (code === undefined || value.code === code);\n}\n\n/** Parse a response body, preserving non-JSON text for error reporting. */\nexport function parseJson(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n","/**\n * EIP-55 for the 40 hex digits of an Ethereum address, on `@noble/hashes` (no ethers): the one\n * place core computes the checksum casing, shared by the typed-data encoder (which refuses a bad\n * mixed-case address) and the gateway writes (which spell an `0x` account as `eth|<checksummed>`).\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\n\nconst textEncoder = new TextEncoder();\n\n/**\n * The EIP-55 casing of 40 hex digits (any case in, no `0x`): a letter is upper-case where the\n * matching nibble of keccak256(lower-case digits) is 8 or more. Byte-identical to ethers'\n * `getAddress(...).slice(2)` for every 40-digit input.\n */\nexport function eip55Digits(digits: string): string {\n const lower = digits.toLowerCase();\n const hash = keccak_256(textEncoder.encode(lower));\n let checksummed = '';\n for (let index = 0; index < lower.length; index += 1) {\n const nibble = ((hash[index >> 1] as number) >> (index % 2 === 0 ? 4 : 0)) & 0xf;\n const char = lower.charAt(index);\n checksummed += nibble >= 8 ? char.toUpperCase() : char;\n }\n return checksummed;\n}\n\n/**\n * True when 40 hex digits carry no checksum (all one case, as EIP-55 allows) or exactly the\n * EIP-55 one. A mixed-case address with any letter in the wrong case is a typo EIP-55 exists to\n * catch, and is refused by every caller.\n */\nexport function hasValidEip55Casing(digits: string): boolean {\n const mixedCase = /[A-F]/u.test(digits) && /[a-f]/u.test(digits);\n return !mixedCase || eip55Digits(digits) === digits;\n}\n\nconst ACCOUNT_DIGITS = /^(?:0x)?([0-9a-fA-F]{40})$/u;\n\n/**\n * An Ethereum account (`0x` plus 40 hex digits, or the 40 digits alone) as `0x` plus its EIP-55\n * checksummed digits, or `undefined` for anything else: another length or character, or a\n * mixed-case spelling whose casing is not the EIP-55 one (a typo EIP-55 exists to catch).\n * Byte-identical to ethers' `getAddress` for every value it accepts.\n *\n * @example\n * ```typescript\n * checksumEthereumAddress('0x70997970c51812dc3a010c7d01b50e0d17dc79c8');\n * // '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'\n * ```\n */\nexport function checksumEthereumAddress(value: string): string | undefined {\n const digits = ACCOUNT_DIGITS.exec(value)?.[1];\n return digits !== undefined && hasValidEip55Casing(digits)\n ? `0x${eip55Digits(digits)}`\n : undefined;\n}\n","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","/**\n * Genuine EIP-712 typed-data signing for the four v2 dex-contract operations, proven by a live\n * bisection against the staging chain to recover the `client|` identity correctly via\n * `eth_signTypedData_v4`, unlike `personal_sign` (which only ever resolves the bare `eth|` form;\n * see `BrowserWalletSigner`'s own doc comment). The field completers mirror the web app's\n * typed-data builders exactly. (Moved from gswap-sdk with the rest of the signing closure; the\n * four methods are dex-contract methods, the derivation is generic.)\n */\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\n\n/** EIP-712 `types`: each struct name mapped to its ordered `{ name, type }` fields. */\nexport type EIP712Types = Record<string, Array<{ name: string; type: string }>>;\n\n/**\n * Derives the EIP-712 `types` for a DTO from its runtime shape.\n *\n * The generated `types` travel with the signed payload and are what BOTH sides hash, so they\n * must enumerate EVERY field the chain-side DTO will carry. GalaChain refuses any signature\n * whose `types` leave a DTO field uncovered (`assertNoUnsignedFields`, the fix for the\n * 2026-08-18 unsigned-field-injection drain); when that happens signature recovery fails\n * outright and the chain reports \"Missing signerPublicKey or signerAddress field in dto\".\n */\nexport function generateEIP712Types(\n typeName: string,\n params: Record<string, unknown>,\n): EIP712Types {\n const types: EIP712Types = {};\n types[typeName] = [];\n\n // Every `name` this is ever called with (the top-level `typeName`, or a nested struct's own\n // name) is unconditionally assigned `types[name] = []` on the line immediately before any\n // recursive call that could reach here; TypeScript still types `types[name]` as\n // possibly-undefined (index-signature access), so the guard below stays for real type safety\n // even though no current call path can actually trigger it.\n function fieldsFor(name: string): Array<{ name: string; type: string }> {\n const fields = types[name];\n /* c8 ignore next */\n if (!fields) throw new Error(`Missing EIP-712 type definition for ${name}`);\n return fields;\n }\n\n function addField(\n name: string,\n fieldValue: unknown,\n parentTypeName: string,\n onlyGetType = false,\n ): string | undefined {\n if (Array.isArray(fieldValue)) {\n const type =\n fieldValue.length > 0 ? addField(name, fieldValue[0], parentTypeName, true) : 'string';\n if (!onlyGetType) fieldsFor(parentTypeName).push({ name, type: (type ?? name) + '[]' });\n } else if (typeof fieldValue === 'object' && fieldValue !== null) {\n if (types[name]) {\n throw new GalaSDKError('EIP712_NAME_COLLISION', { name });\n }\n types[name] = [];\n Object.entries(fieldValue).forEach(([key, value]) => {\n addField(key, value, name);\n });\n if (!onlyGetType) fieldsFor(parentTypeName).push({ name, type: name });\n } else {\n let eipType: string;\n switch (typeof fieldValue) {\n case 'string':\n eipType = 'string';\n break;\n case 'number':\n eipType = 'int256';\n break;\n case 'boolean':\n eipType = 'bool';\n break;\n case 'bigint':\n case 'symbol':\n case 'undefined':\n case 'function':\n case 'object':\n throw new GalaSDKError('EIP712_UNSUPPORTED_VALUE', { valueType: typeof fieldValue });\n }\n if (onlyGetType) {\n return eipType;\n }\n fieldsFor(parentTypeName).push({ name, type: eipType });\n }\n return undefined;\n }\n\n Object.entries(params).forEach(([key, value]) => {\n addField(key, value, typeName);\n });\n\n return types;\n}\n\n/** The EIP-712 domain carried by a signed payload: GalaChain only uses `name` and `chainId`. */\nexport interface EIP712DomainValue {\n name: string;\n chainId: number;\n}\n\n/**\n * Builds the EIP-712 domain from the wallet's LIVE `eth_chainId` result: a wallet hashes whatever\n * domain it is handed, and MetaMask refuses a `chainId` that differs from its active network, so\n * a hardcoded `1` breaks every wallet that is not on Mainnet.\n * The backend recovers the signer from the `domain` the payload carries (live-proven for chain\n * ids 1, 56 and 11155111), so following the wallet is correct on every network.\n *\n * @param chainId - The raw `eth_chainId` result: a `0x` hex string (the JSON-RPC form) or an integer.\n * @param name - The domain name the deployment requires (`GALA_CHAIN_ENVIRONMENTS[env].eip712DomainName`);\n * `'ethereum'`, what every signer has always signed, when absent.\n * @throws GalaSDKError (`INVALID_CHAIN_ID`) when the wallet answers with anything else.\n */\nexport function eip712DomainFor(chainId: unknown, name = 'ethereum'): EIP712DomainValue {\n const parsed =\n typeof chainId === 'string' && /^0x[0-9a-fA-F]+$/u.test(chainId)\n ? Number(chainId)\n : typeof chainId === 'number'\n ? chainId\n : Number.NaN;\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new GalaSDKError('INVALID_CHAIN_ID', {\n chainId:\n typeof chainId === 'string' || typeof chainId === 'number'\n ? String(chainId)\n : typeof chainId,\n });\n }\n return { name, chainId: parsed };\n}\n\n/**\n * The four v2 operations proven to recover the signer correctly via genuine EIP-712: `RequestTrade`\n * never had the problem (one numeric field). `AddLiquidity`/`RemoveLiquidity`/\n * `CollectPositionFees` each need their `types` completed with a handful of fields their real\n * server-side DTO always carries — see the `complete*Fields` functions below. `CreatePool` is a\n * genuinely different, unsolved problem (nested `TokenClassKey` structs, not a flat\n * missing-field gap) and is NOT in this set — callers must keep using `personal-sign` for it.\n */\nexport const EIP712_CAPABLE_METHODS: ReadonlySet<string> = new Set([\n 'RequestTrade',\n 'AddLiquidity',\n 'RemoveLiquidity',\n 'CollectPositionFees',\n]);\n\n/**\n * Every `complete*Fields` function below shares the same two live-proven rules:\n * 1. Numeric completeness fields MUST be JS `number`, never numeric strings —\n * `generateEIP712Types` infers a field's Solidity type from `typeof`, and declaring one as\n * EIP-712 `string` instead of `int256` breaks recovery identically to omitting the field\n * entirely (verified live on AddLiquidity: `amount0Min: '0'` fails with the exact same\n * \"Missing signerPublicKey\" error as `amount0Min` being absent; `amount0Min: 0` succeeds).\n * 2. `positionId` has no such constraint — an empty string works, and does not target an\n * existing position (`positionId: ''` created a fresh position on AddLiquidity, not an add\n * to position id `''`; on RemoveLiquidity/CollectPositionFees the real position is still\n * resolved from `token0`/`token1`/`fee`/`tickLower`/`tickUpper`, not from this field).\n */\nfunction numericOr0(dto: Record<string, unknown>, field: string): number {\n return typeof dto[field] === 'number' ? dto[field] : 0;\n}\n\n/**\n * `AddLiquidity`'s real server-side DTO always carries `amount0Desired`/`amount0Min`/\n * `amount1Desired`/`amount1Min`/`positionId` once reconstructed, regardless of which deposit\n * convention the caller used (`Positions.addLiquidityByTicks` only ever sends\n * `depositQuantityToken0`/`depositQuantityToken1`). Proven empirically by bisection: none of the\n * five alone fixes recovery, all five together does (live 201, tx `407d9b24...`, block\n * `2429022`).\n */\nfunction completeAddLiquidityFields(dto: Record<string, unknown>): Record<string, unknown> {\n return {\n ...dto,\n amount0Desired: numericOr0(dto, 'amount0Desired'),\n amount0Min: numericOr0(dto, 'amount0Min'),\n amount1Desired: numericOr0(dto, 'amount1Desired'),\n amount1Min: numericOr0(dto, 'amount1Min'),\n positionId: dto['positionId'] ?? '',\n };\n}\n\n/**\n * `RemoveLiquidity`'s real server-side DTO always carries `amount`/`amount0Min`/`amount1Min`/\n * `positionId` — `Positions.removeLiquidity` only ever sends a `withdrawalQuantityTokenX` (or\n * neither, for a full close). Proven empirically: every subset of these four fails, all four\n * together succeeds (live, random-signer probe — recovery confirmed by the response moving from\n * \"Missing signerPublicKey\" to a genuine position-not-found 404).\n */\nfunction completeRemoveLiquidityFields(dto: Record<string, unknown>): Record<string, unknown> {\n return {\n ...dto,\n amount: numericOr0(dto, 'amount'),\n amount0Min: numericOr0(dto, 'amount0Min'),\n amount1Min: numericOr0(dto, 'amount1Min'),\n positionId: dto['positionId'] ?? '',\n };\n}\n\n/**\n * `CollectPositionFees`'s real server-side DTO always carries `amount0Requested`/\n * `amount1Requested`/`positionId` — `Positions.collectPositionFees` sends only the five identity\n * fields. Proven empirically the same way as `completeRemoveLiquidityFields`.\n */\nfunction completeCollectPositionFeesFields(dto: Record<string, unknown>): Record<string, unknown> {\n return {\n ...dto,\n amount0Requested: numericOr0(dto, 'amount0Requested'),\n amount1Requested: numericOr0(dto, 'amount1Requested'),\n positionId: dto['positionId'] ?? '',\n };\n}\n\nexport const EIP712_FIELD_COMPLETERS: Readonly<\n Record<string, (dto: Record<string, unknown>) => Record<string, unknown>>\n> = {\n AddLiquidity: completeAddLiquidityFields,\n RemoveLiquidity: completeRemoveLiquidityFields,\n CollectPositionFees: completeCollectPositionFeesFields,\n};\n\n/**\n * Completes a DTO's fields for EIP-712 signing (a no-op for methods with no known gap, e.g.\n * `RequestTrade`) and derives its `types`. Exported separately from the signing call itself so tests\n * can assert on the exact payload without needing a live provider.\n */\nexport function buildEIP712Payload(\n methodName: string,\n dto: Record<string, unknown>,\n): { completedDto: Record<string, unknown>; types: EIP712Types } {\n const completer = EIP712_FIELD_COMPLETERS[methodName];\n const completedDto = completer ? completer(dto) : dto;\n const types = generateEIP712Types(methodName, completedDto);\n return { completedDto, types };\n}\n","/**\n * SDK-owned signing primitives.\n *\n * Everything the SDK needs to produce a GalaChain signature lives here, with no dependency on\n * `@gala-chain/api` (which drags `secp256k1` native bindings, `reflect-metadata`, `class-validator`\n * and its own `bignumber.js` major into every consumer). The only runtime dependencies are the\n * audited, pure-JS `@noble/curves` (secp256k1) and `@noble/hashes` (keccak256), which run\n * unchanged in browsers, MV3 service workers, Node and React Native/Hermes.\n *\n * Every function here is pinned byte-for-byte to the signatures produced by `@gala-chain/api`\n * (`serialize`, `signatures.getSignature`), `@gala-chain/connect`, the Gala Wallet extension and\n * the gSwap web app by the golden-vector suite in `tests/signing-golden.test.ts`.\n */\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\nimport type { InvalidPrivateKeyReason } from '../classes/error_catalog.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\n\nconst textEncoder = new TextEncoder();\n\nfunction toDeterministicNode(node: unknown): unknown {\n if (node === null || node === undefined) return node;\n if (node instanceof RegExp) return node.toString();\n const candidate = node as { toJSON?: unknown };\n return typeof candidate.toJSON === 'function'\n ? (Reflect.apply(candidate.toJSON, node, []) as unknown)\n : node;\n}\n\nfunction deterministicNode(rawNode: unknown): string | undefined {\n const node = toDeterministicNode(rawNode);\n if (node === undefined) return undefined;\n if (typeof node !== 'object' || node === null) return JSON.stringify(node);\n\n if (Array.isArray(node)) {\n const items = (node as unknown[]).map((item) => deterministicNode(item) ?? 'null');\n return `[${items.join(',')}]`;\n }\n\n const record = node as Record<string, unknown>;\n const members: string[] = [];\n for (const key of Object.keys(record).sort()) {\n const value = deterministicNode(record[key]);\n if (value === undefined) continue;\n members.push(`${JSON.stringify(key)}:${value}`);\n }\n return `{${members.join(',')}}`;\n}\n\n/**\n * GalaChain's deterministic JSON: object keys sorted (UTF-16 code-unit order) at every depth, no\n * whitespace, `undefined`/function members dropped, `toJSON()` honored. Byte-identical to\n * `serialize` from `@gala-chain/api` / `json-stringify-deterministic` for every JSON-shaped\n * value, which is all a DTO ever is.\n *\n * @throws TypeError for circular structures and BigInt values (as `JSON.stringify` does) and\n * when the value itself has no JSON representation (`undefined`, a function, a symbol).\n */\nexport function serialize(value: unknown): string {\n // Same cycle/BigInt guard json-stringify-deterministic runs before walking the value.\n JSON.stringify(value);\n const result = deterministicNode(value);\n if (result === undefined) {\n throw new TypeError('Cannot serialize a value with no JSON representation.');\n }\n return result;\n}\n\n/**\n * The exact string GalaChain hashes for a DTO: the (optional, string) `prefix` field PREPENDED to\n * the deterministic serialization of the DTO WITHOUT `signature`, `multisig`, `trace` and `prefix`.\n * Equivalent to `@gala-chain/api` 3.x `getPayloadToSign` for every non-EIP-712 DTO.\n */\nexport function getPayloadToSign(dto: Record<string, unknown>): string {\n const { prefix, ...rest } = dto;\n delete rest['signature'];\n delete rest['multisig'];\n delete rest['trace'];\n const head = typeof prefix === 'string' ? prefix : '';\n return head + serialize(rest);\n}\n\n// Built via String.fromCharCode rather than a literal escape ON PURPOSE: a literal control byte in\n// source is invisible and fragile under editors/diffs/copy-paste; this keeps the source ordinary.\nconst ETHEREUM_SIGNED_MESSAGE = String.fromCharCode(0x19) + 'Ethereum Signed Message:\\n';\n\n/**\n * The EIP-191 header for `message`: `\"\\x19Ethereum Signed Message:\\n\"` + the message's UTF-8 BYTE\n * length. This is what a wallet's `personal_sign` prepends, and what the chain recomputes when it\n * recovers a personal-signed DTO.\n */\nexport function calculatePersonalSignPrefix(message: string): string {\n return ETHEREUM_SIGNED_MESSAGE + String(textEncoder.encode(message).length);\n}\n\n/**\n * The EIP-191 header for `serialize(dto)` (any `prefix` already on the DTO is ignored). This is\n * deliberately the same string the signers hand a wallet to sign, so the header's length can never\n * disagree with the signed message. Wallet-neutral: it is the value both a browser wallet's\n * `personal_sign` and Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepend.\n */\nexport function personalSignPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n return calculatePersonalSignPrefix(serialize(withoutPrefix));\n}\n\n/**\n * The `@gala-chain/connect`-style prefix the gSwap web app puts in the body of an EIP-712 write: the\n * EIP-191 header whose number counts the prefix string ITSELF plus the body (the UTF-8 length of\n * `getPayloadToSign({ ...dto, prefix })`), found by fixpoint because adding the prefix changes the\n * length (a body of 99 bytes settles on 101).\n *\n * It is NOT a personal-sign prefix (a personal-sign write with this value recovers a phantom\n * signer; use `personalSignPrefixFor`). Under EIP-712 the field is an untyped extra that the\n * typed-data hash ignores and the backend recomputes, so it only exists to keep the submitted\n * body byte-identical to what the gSwap web app has always sent.\n */\nexport function fixpointPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n let payloadLength = textEncoder.encode(getPayloadToSign(withoutPrefix)).length;\n let prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n let previousLength = -1;\n while (payloadLength !== previousLength) {\n previousLength = payloadLength;\n prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n payloadLength = textEncoder.encode(getPayloadToSign({ ...withoutPrefix, prefix })).length;\n }\n return prefix;\n}\n\nfunction invalidPrivateKey(reason: InvalidPrivateKeyReason): GalaSDKError<'INVALID_PRIVATE_KEY'> {\n return new GalaSDKError('INVALID_PRIVATE_KEY', { reason });\n}\n\nconst BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nfunction decodeBase64(input: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(input) || input.length % 4 !== 0) return undefined;\n const unpadded = input.replace(/=+$/u, '');\n const bytes: number[] = [];\n let buffer = 0;\n let bits = 0;\n for (const char of unpadded) {\n buffer = (buffer << 6) | BASE64_ALPHABET.indexOf(char);\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((buffer >> bits) & 0xff);\n }\n }\n return Uint8Array.from(bytes);\n}\n\nfunction decodeHex(input: string): Uint8Array {\n const bytes = new Uint8Array(input.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = parseInt(input.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Normalizes a secp256k1 private key to a fresh 32-byte array (the caller may zero it). Also\n * accepts 32 raw bytes, which are validated and copied. For strings it accepts what `@gala-chain/api`'s\n * `normalizePrivateKey` accepted for a usable key: 64 hex characters (optionally `0x`-prefixed;\n * a 63-character hex key is left-padded with a zero) or a 44-character base64 string.\n *\n * @throws GalaSDKError (`INVALID_PRIVATE_KEY`; `params.reason` is one of\n * `INVALID_PRIVATE_KEY_REASONS`: `wrong_length` for raw bytes that are not 32 long,\n * `bad_encoding` for any other string shape, `not_on_curve` for an out-of-range scalar).\n */\nexport function normalizePrivateKey(input: string | Uint8Array): Uint8Array {\n if (typeof input !== 'string') {\n // Raw bytes: validated, then COPIED, so zeroing the result never touches the caller's array.\n if (!(input instanceof Uint8Array) || input.length !== 32) {\n throw invalidPrivateKey('wrong_length');\n }\n if (!secp256k1.utils.isValidSecretKey(input)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return Uint8Array.from(input);\n }\n const withoutPrefix = input.startsWith('0x') ? input.slice(2) : input;\n let key: Uint8Array | undefined;\n if (/^[0-9a-fA-F]{63,64}$/u.test(withoutPrefix)) {\n key = decodeHex(withoutPrefix.length === 63 ? `0${withoutPrefix}` : withoutPrefix);\n } else if (withoutPrefix.length === 44) {\n key = decodeBase64(withoutPrefix);\n }\n if (key?.length !== 32) {\n throw invalidPrivateKey('bad_encoding');\n }\n if (!secp256k1.utils.isValidSecretKey(key)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return key;\n}\n\n/**\n * Signs a 32-byte keccak256 hash and returns GalaChain's recoverable signature: 64 hex `r` +\n * 64 hex `s` + `1b`/`1c` (`v`), lowercase, no `0x`. Deterministic (RFC 6979) and low-S, exactly\n * what `@gala-chain/api` and the Gala Wallet produce. A DER signature carries no recovery byte\n * and cannot be used: the chain RECOVERS the signer from the signature.\n */\nexport function signHash(privateKey: Uint8Array, hash: Uint8Array): string {\n if (hash.length !== 32) {\n throw new GalaSDKError('INVALID_SIGNING_HASH_LENGTH', { length: hash.length });\n }\n const signature = secp256k1.sign(hash, privateKey, { prehash: false, lowS: true });\n // compact raw bytes are r (32) || s (32); the recovery id becomes v.\n return bytesToHex(signature.toBytes('compact')) + (signature.recovery === 1 ? '1c' : '1b');\n}\n\n/**\n * The lowercase `0x` Ethereum address (last 20 bytes of keccak256 of the uncompressed public key)\n * of a normalized private key. The Gala `eth|` identity of a key is this address.\n */\nexport function ethAddressOfPrivateKey(privateKey: Uint8Array): string {\n const publicKey = secp256k1.getPublicKey(privateKey, false);\n return `0x${bytesToHex(keccak_256(publicKey.slice(1)).slice(-20))}`;\n}\n\n/** keccak256 of a string's UTF-8 bytes. */\nexport function keccak256Utf8(data: string): Uint8Array {\n return keccak_256(textEncoder.encode(data));\n}\n\n/**\n * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes, with no\n * prefix and no signature envelope. The caller owns serialization, so the bytes shown to a user\n * and the bytes signed can never diverge.\n */\nexport function signSerializedNative(privateKey: Uint8Array, serializedDto: string): string {\n return signHash(privateKey, keccak256Utf8(serializedDto));\n}\n\n/**\n * GalaChain NATIVE signature for a DTO: keccak256 of `getPayloadToSign(dto)`, signed with\n * secp256k1. Byte-identical to `signatures.getSignature` from `@gala-chain/api`.\n */\nexport function signNative(privateKey: Uint8Array, dto: Record<string, unknown>): string {\n return signSerializedNative(privateKey, getPayloadToSign(dto));\n}\n\n/**\n * Personal-sign hash and signature: keccak256(`prefix` + `message`), both hashed VERBATIM with no\n * further EIP-191 wrapping. Passing `prefix = calculatePersonalSignPrefix(message)` reproduces a\n * wallet's `personal_sign` of `message`. Gala Wallet's `gala_signChainDto` (personal-sign\n * scheme) hashes `prefix` + the exact string it is handed, which can differ from the bare message\n * (see the `signatureOverPrefixlessBody` vectors); that quirk is why the two inputs stay separate.\n */\nexport function signPersonalMessage(\n privateKey: Uint8Array,\n prefix: string,\n message: string,\n): string {\n return signHash(privateKey, keccak256Utf8(prefix + message));\n}\n","import { GalaSDKError, isGalaError } from './gala_sdk_error.js';\nimport { assertNoEthZeroXPrefix } from '../writes/identity.js';\nimport {\n buildEIP712Payload,\n EIP712_CAPABLE_METHODS,\n eip712DomainFor,\n type EIP712DomainValue,\n type EIP712Types,\n} from '../utils/eip712.js';\nimport {\n ethAddressOfPrivateKey,\n fixpointPrefixFor,\n normalizePrivateKey,\n personalSignPrefixFor,\n serialize,\n signNative,\n} from '../utils/signing.js';\n\n// Personal-sign prefix, computed the way THE CHAIN verifies it.\n//\n// GalaChain (SDK 3.x) recovers a personal-signed DTO from\n// keccak256(<prefix field> + <canonical JSON of the DTO WITHOUT the prefix field>)\n// and a browser wallet's `personal_sign` (EIP-191) hashes\n// \"\\u0019Ethereum Signed Message:\\n\" + <byte length of message> + <message>.\n// They agree exactly when the wallet signs the bare canonical DTO and `prefix` is the EIP-191\n// header for that message's UTF-8 BYTE length. Any other message still yields a valid-looking\n// signature — it just recovers to an address nobody holds. This SDK used to embed `prefix` in\n// the signed message (the SDK 1.10 client recipe): observed on stage 2026-09-23, such a\n// MetaMask-signed CreatePool executed on chain under a phantom creator, and the swap backend's\n// write guard now rejects that shape outright.\n//\n// `@gala-chain/connect`'s prefix helper must NOT be used for wallet `personal_sign`: its\n// fixpoint counts the prefix itself and targets the SDK's raw-payload signer. The same header\n// is also what Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepends before hashing,\n// so one value serves both paths.\n//\n// The header itself is computed by `personalSignPrefixFor` in ../utils/signing.ts.\n\n/** The signing schemes supported by the Gala Wallet signer. */\nexport type GalaWalletScheme = 'native' | 'personal-sign';\n\n/** The request surface used by an EIP-1193 browser wallet. */\nexport interface BrowserWalletProvider {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n}\n\n/** The Gala Wallet extension's API (`window.gala`, or the same object from an EIP-6963 announcement). */\nexport interface GalaWalletApi {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n /** Gala Wallet's \"act as this account\" switch; absent on other providers. */\n setAddress?: (address: string) => Promise<void>;\n}\n\ninterface WindowWithGala {\n gala?: GalaWalletApi;\n}\n\ninterface GlobalWithWindow {\n window?: WindowWithGala;\n}\n\n/** A DTO together with the signature that belongs in the gateway request body. */\nexport type SignedDto<T extends Record<string, unknown>> = T & { signature: string };\n\n/**\n * A signer for complete GalaChain write bodies.\n *\n * Implementations return the DTO fields together with the signature that belongs in the\n * gateway request body. Signer identity is recovered from that signature; implementations do\n * not add signer hints, typed-data metadata, or a domain.\n */\nexport interface GalaChainSigner {\n /**\n * Signs a DTO for a named GalaChain contract method.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n signObject<T extends Record<string, unknown>>(methodName: string, dto: T): Promise<SignedDto<T>>;\n}\n\nfunction getWalletProvider(): GalaWalletApi {\n const globalObject = globalThis as GlobalWithWindow;\n const wallet = globalObject.window?.gala;\n if (!wallet) {\n throw new GalaSDKError('GALA_WALLET_NOT_AVAILABLE', {});\n }\n return wallet;\n}\n\nfunction getNativeSignature(value: unknown): string {\n if (typeof value !== 'string') {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n // 130 hex digits (r || s || v), bare as Gala Wallet returns it or `0x`-prefixed; passed on\n // verbatim, because the backend recovers the signer from either spelling.\n if (!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n return value;\n}\n\nfunction getPersonalSignature(value: unknown): string {\n if (typeof value !== 'string' || !/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'personal-sign' });\n }\n return value;\n}\n\n/**\n * The `0x`-prefixed Ethereum address a Gala account is signed by, or `undefined` when the account\n * names no key (a `client|` alias or a bare GalaChain id is not derivable from a key). Accepts\n * `0x` plus 40 hex digits and `eth|` plus 40 hex digits; the caller's casing is kept. `eth|0x...`\n * is not an address form and is refused. For {@link LazyPrivateKeySignerOptions.expectedAddress}, which should only be set for\n * an account whose key can be checked.\n *\n * @example\n * ```ts\n * createLazyPrivateKeySigner(getKey, { expectedAddress: ethereumAddressOfAccount(account) });\n * ```\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` for `eth|0x...` (refused, never read as\n * \"names no key\", which would switch a signer's address check off).\n */\nexport function ethereumAddressOfAccount(account: string): string | undefined {\n assertNoEthZeroXPrefix(account, 'account');\n const match = /^(?:eth\\||0x)([0-9a-fA-F]{40})$/u.exec(account);\n return match?.[1] === undefined ? undefined : `0x${match[1]}`;\n}\n\nfunction normalizeEthereumAccount(\n address: string,\n allowGalaPrefix: boolean,\n field = 'walletAddress',\n): string {\n assertNoEthZeroXPrefix(address, field);\n const normalized = allowGalaPrefix ? (ethereumAddressOfAccount(address) ?? address) : address;\n if (!/^0x[0-9a-fA-F]{40}$/u.test(normalized)) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field, value: address });\n }\n // The caller's casing is kept on purpose: the Gala web apps and the wallet hand the wallet the\n // checksummed account, and EIP-1193 / Gala Wallet accept any case, so passing the value through\n // unchanged is the only choice that cannot differ from what they send.\n return normalized;\n}\n\n/**\n * The account handed to Gala Wallet as the signer address. An Ethereum account is held to the\n * same strict check as ever (`0x` plus 40 hex digits; `eth|` plus 40 hex digits is normalized to\n * it; `eth|0x...` is refused). A GalaChain id the wallet can also be asked to sign for is passed\n * through verbatim: `client|` plus 24 hex digits, or the bare 24 hex digits that a web app keeps\n * after a direct `client|` login. Nothing else is accepted.\n */\nfunction normalizeGalaWalletAccount(address: string): string {\n assertNoEthZeroXPrefix(address, 'walletAddress');\n const eth = /^eth\\|([0-9a-fA-F]{40})$/u.exec(address);\n if (eth?.[1] !== undefined) return `0x${eth[1]}`;\n if (/^0x[0-9a-fA-F]{40}$/u.test(address) || /^(?:client\\|)?[0-9a-fA-F]{24}$/u.test(address)) {\n return address;\n }\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field: 'walletAddress', value: address });\n}\n\n/** An identity Gala Wallet can act as: an account form above, any `eth|`/`client|` alias, verbatim. */\nfunction assertWalletIdentity(identity: string): void {\n assertNoEthZeroXPrefix(identity, 'selectAddress');\n if (\n !/^(?:eth\\|[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\\|)?[0-9a-fA-F]{24})$/u.test(identity)\n ) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field: 'selectAddress', value: identity });\n }\n}\n\n/** Provider-wide queue: `setAddress` + the signature request must not interleave across signers. */\nconst walletIdentityQueue = new WeakMap<object, Promise<unknown>>();\n\n/**\n * Runs `signWith` with `identity` selected on a Gala Wallet that supports `setAddress`. Gala\n * Wallet holds ONE current account, so two signatures for different identities in flight at once\n * would sign as whichever selection came last; the pair (select, sign) is therefore serialized\n * per wallet object, across every signer and provider that signs through it\n * (`GalaWalletSigner`, `./providers`' `GalaWalletProvider`). A failed selection fails the\n * signature (nothing is requested). Without an identity, or on a wallet without `setAddress`, it\n * just runs `signWith`.\n *\n * @example\n * ```typescript\n * const signature = await withGalaWalletIdentity(window.gala, 'eth|70997970C51812dc3A010C7d01b50e0d17dc79C8', () =>\n * window.gala.request({ method: 'personal_sign', params: [hexMessage, address] }),\n * );\n * ```\n */\nexport function withGalaWalletIdentity<T>(\n wallet: GalaWalletApi,\n identity: string | undefined,\n signWith: () => Promise<T>,\n): Promise<T> {\n const { setAddress } = wallet;\n if (identity === undefined || typeof setAddress !== 'function') return signWith();\n const previous = walletIdentityQueue.get(wallet) ?? Promise.resolve();\n const run = previous\n .catch(() => undefined)\n .then(async () => {\n await setAddress.call(wallet, identity);\n return signWith();\n });\n walletIdentityQueue.set(wallet, run);\n return run;\n}\n\nfunction personalSign<T extends Record<string, unknown>>(\n provider: GalaWalletApi | BrowserWalletProvider,\n dto: T,\n walletAddress: string,\n methodName?: string,\n): Promise<T & { prefix: string; signature: string }> {\n const prefix = personalSignPrefixFor(dto);\n const payload = { ...dto, prefix };\n // A browser wallet's `personal_sign` applies the EIP-191 header ITSELF, so it must sign the\n // bare DTO; Gala Wallet's `gala_signChainDto` (personal-sign scheme) instead extracts the\n // `prefix` field from what it is handed and prepends it before hashing, so it is handed the\n // prefixed payload. Both submit `{ ...dto, prefix, signature }`.\n const params =\n methodName !== undefined\n ? [serialize(payload), walletAddress, methodName]\n : [serialize(dto), walletAddress];\n\n return provider\n .request({ method: methodName !== undefined ? 'gala_signChainDto' : 'personal_sign', params })\n .then((value) => ({ ...payload, signature: getPersonalSignature(value) }));\n}\n\n/**\n * Signs a DTO via genuine EIP-712 (`eth_signTypedData_v4`) — correctly resolves the `client|`\n * identity, unlike `personal_sign`, for the operations in `EIP712_CAPABLE_METHODS`.\n *\n * Constructs the raw JSON-RPC payload by hand (`{domain, types: {...types, EIP712Domain},\n * primaryType, message}`) rather than depending on ethers.js, matching exactly what\n * `ethers.TypedDataEncoder.getPayload`/`Wallet.signTypedData` produce internally — verified\n * byte-for-byte equivalent (same recovered address from the same signature against both\n * constructions) before this shipped, since the core SDK deliberately has no ethers dependency.\n */\nasync function signEIP712<T extends Record<string, unknown>>(\n provider: BrowserWalletProvider,\n methodName: string,\n dto: T,\n walletAddress: string,\n domainName?: string,\n): Promise<T & { types: EIP712Types; domain: EIP712DomainValue; signature: string }> {\n const { completedDto, types } = buildEIP712Payload(methodName, dto);\n // The wallet's LIVE chain id, read on every signature: a user can switch networks after\n // connecting, and a cached or hardcoded id would sign a domain MetaMask itself rejects. The\n // name is the deployment's (`eip712DomainName`), `ethereum` when none is given.\n const domain = eip712DomainFor(\n await provider.request({ method: 'eth_chainId', params: [] }),\n domainName,\n );\n // The body `prefix` is not part of the EIP-712 `types`, so it is never hashed; it carries the\n // connect-style fixpoint value only to keep the submitted body byte-identical to what the Gala\n // web apps have always sent.\n const prefix = fixpointPrefixFor(completedDto);\n const message = { ...completedDto, prefix };\n const eip712Domain = [\n { name: 'name', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n ];\n const payload = {\n domain,\n types: { ...types, EIP712Domain: eip712Domain },\n primaryType: methodName,\n message,\n };\n\n const value = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [walletAddress, JSON.stringify(payload)],\n });\n // Key order matches the body the Gala web apps submit: ..., prefix, signature, types, domain.\n return {\n ...(message as T & { prefix: string }),\n signature: getPersonalSignature(value),\n types,\n domain,\n };\n}\n\n/**\n * A GalaChain native signer backed by a secp256k1 private key.\n *\n * Native signing produces the bare GalaChain signature format, without a personal-sign prefix\n * or EIP-712 metadata. The private-key identity is recovered by the chain.\n */\nexport class PrivateKeySigner implements GalaChainSigner {\n private readonly privateKey: Uint8Array;\n\n /**\n * Creates a native signer from a hex or base64 secp256k1 private key.\n *\n * @example\n * ```typescript\n * const signer = new PrivateKeySigner('1'.padStart(64, '0'));\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n constructor(privateKey: string) {\n this.privateKey = normalizePrivateKey(privateKey);\n }\n\n /**\n * Signs the DTO with GalaChain native signing.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const signature = signNative(this.privateKey, dto);\n return Promise.resolve({ ...dto, signature });\n }\n}\n\n/** Supplies a private key at sign time: a hex/base64 string, possibly fetched asynchronously. */\nexport type PrivateKeyProvider = () => Promise<string> | string;\n\n/** Options for {@link createLazyPrivateKeySigner}. */\nexport interface LazyPrivateKeySignerOptions {\n /**\n * When set, every signature first checks that the fetched key belongs to this account (`0x...`\n * or the Gala `eth|<40 hex>` form, case-insensitive; `eth|0x...` is refused at creation) and\n * refuses to sign otherwise (`SIGNER_ADDRESS_MISMATCH`). Use it when the key lives in a slot another surface can switch\n * between the moment a request was approved and the moment it is signed.\n */\n expectedAddress?: string | undefined;\n}\n\n/**\n * Calls the app's key provider. Whatever it throws or rejects with is the app's own failure to\n * produce a key before anything was signed or sent, so it becomes `KEY_PROVIDER_FAILED` (the\n * original is `cause`); an SDK error is already catalogued and passes through.\n */\nasync function keyFrom(getPrivateKey: PrivateKeyProvider): Promise<unknown> {\n try {\n return await getPrivateKey();\n } catch (cause: unknown) {\n throw isGalaError(cause) ? cause : new GalaSDKError('KEY_PROVIDER_FAILED', {}, { cause });\n }\n}\n\n/**\n * Creates the native-signing equivalent of {@link PrivateKeySigner} for apps that must not hold a\n * key in a long-lived object (an extension that reads its session key at sign time).\n *\n * `getPrivateKey` is called once per `signObject` call, never cached, never shared between calls\n * (concurrent signatures each fetch their own key), and the normalized key bytes are zeroed\n * before `signObject` settles, also on failure. A rejection or exception from `getPrivateKey` (the\n * app's \"wallet is locked\", a storage read that failed) is a `KEY_PROVIDER_FAILED` error with the\n * original error as `cause`: nothing has been sent, so `classifyFailure` says `not_sent` and Retry\n * is safe, and the app needs no error class of its own to tell this apart. A provider that returns\n * no usable string (`''`, `undefined`) is `INVALID_PRIVATE_KEY` with `reason: 'no_key_provided'`,\n * classified the same way; any other key that is not a valid secp256k1 key string is an\n * `INVALID_PRIVATE_KEY` error. An SDK error the provider throws itself is passed through.\n * Signatures are byte-identical to `new PrivateKeySigner(key).signObject(...)`.\n *\n * A JavaScript string cannot be wiped; the provider owns the lifetime of the string it returns.\n *\n * @example\n * ```typescript\n * const signer = createLazyPrivateKeySigner(\n * () => SecurityHelper.getSessionSecret(SecurityHelper.SESSION_PRIVATE_KEY_KEY),\n * { expectedAddress: account.address },\n * );\n * const gswap = new GSwap({ signer });\n * ```\n */\nexport function createLazyPrivateKeySigner(\n getPrivateKey: PrivateKeyProvider,\n options: LazyPrivateKeySignerOptions = {},\n): GalaChainSigner {\n const expected = options.expectedAddress;\n const expectedLower =\n expected === undefined\n ? undefined\n : normalizeEthereumAccount(expected, true, 'expectedAddress').toLowerCase();\n\n return {\n async signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const provided: unknown = await keyFrom(getPrivateKey);\n if (typeof provided !== 'string' || provided === '') {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'no_key_provided' });\n }\n const key = normalizePrivateKey(provided);\n try {\n if (expectedLower !== undefined && ethAddressOfPrivateKey(key) !== expectedLower) {\n throw new GalaSDKError('SIGNER_ADDRESS_MISMATCH', {});\n }\n return { ...dto, signature: signNative(key, dto) };\n } finally {\n key.fill(0);\n }\n },\n };\n}\n\n/**\n * A Gala Wallet signer using native GalaChain signing, with an opt-in personal-sign mode.\n *\n * The selected Ethereum account is passed to Gala Wallet. There is NO automatic fallback: a\n * wallet that rejects `native` surfaces its error to the caller, because the only alternative,\n * `personal-sign`, silently recovers a phantom signer on every released Gala Wallet.\n *\n * `scheme: 'personal-sign'` calls\n * `gala_signChainDto([serialize({ ...dto, prefix }), walletAddress, methodName])` and REQUIRES\n * a Gala Wallet build that strips the embedded `prefix` field and hashes `prefix` + the\n * prefix-less canonical body (the chain's scheme). Wallet builds that predate that fix hash the\n * string with the `prefix` field still inside it and the signature recovers to an address\n * nobody holds, so only opt in once the wallet you target has the fix.\n */\nexport class GalaWalletSigner implements GalaChainSigner {\n /** The wallet address supplied to Gala Wallet for each signing request. */\n public readonly walletAddress: string;\n\n /** The signing scheme used for every request; it never changes after construction. */\n public readonly scheme: GalaWalletScheme;\n\n /**\n * Creates a Gala Wallet signer.\n *\n * @example\n * ```typescript\n * const signer = new GalaWalletSigner('0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n *\n * @param walletAddress - The account passed to Gala Wallet as the signer address. An Ethereum\n * account is `0x` plus 40 hex digits (Gala Wallet's `eth|...` form is normalized to it and held\n * to the same check); a GalaChain id is `client|` plus 24 hex digits, or the bare 24 hex digits\n * a web app keeps for a direct `client|` login, and is passed through unchanged.\n * @param options - Select native signing (default) or personal-sign explicitly.\n * `'personal-sign'` requires a Gala Wallet build that signs the bare serialized DTO.\n * `selectAddress` is the identity (`client|...` / `eth|...`) Gala Wallet is switched to with\n * `setAddress` before every signature, when the wallet offers it. `wallet` is the Gala Wallet\n * object to sign through (the one an EIP-6963 announcement or a wallet provider holds); without\n * it, `window.gala` is read at every signature.\n */\n constructor(\n walletAddress: string,\n options: {\n scheme?: GalaWalletScheme | undefined;\n selectAddress?: string | undefined;\n wallet?: GalaWalletApi | undefined;\n } = {},\n ) {\n this.walletAddress = normalizeGalaWalletAccount(walletAddress);\n this.scheme = options.scheme ?? 'native';\n if (options.selectAddress !== undefined) assertWalletIdentity(options.selectAddress);\n this.selectAddress = options.selectAddress;\n this.wallet = options.wallet;\n }\n\n /** The identity Gala Wallet is switched to before each signature, if one was given. */\n public readonly selectAddress: string | undefined;\n\n /** The Gala Wallet object this signer signs through; `undefined` reads `window.gala` each time. */\n private readonly wallet: GalaWalletApi | undefined;\n\n /**\n * Signs a DTO through `gala_signChainDto`.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('AddLiquidity', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * tickLower: -60,\n * tickUpper: 60,\n * });\n * ```\n */\n public async signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const wallet = this.wallet ?? getWalletProvider();\n\n return withGalaWalletIdentity(wallet, this.selectAddress, async () => {\n if (this.scheme === 'personal-sign') {\n return personalSign(wallet, dto, this.walletAddress, methodName);\n }\n const signature = await wallet.request({\n method: 'gala_signChainDto',\n params: [serialize(dto), this.walletAddress, methodName, 'native'],\n });\n return { ...dto, signature: getNativeSignature(signature) };\n });\n }\n}\n\n/**\n * A personal-sign signer for MetaMask and other EIP-1193 browser wallets.\n *\n * The chain recovers this signature using the EIP-191 wrap applied by the wallet to\n * `personal_sign`. This is the browser-wallet path used by the v2 frontend and resolves the\n * bare `eth|` identity.\n */\nexport class BrowserWalletSigner implements GalaChainSigner {\n /**\n * Creates a browser-wallet signer.\n *\n * Defaults to `personal_sign` — unchanged from every existing integration, since it only ever\n * resolves the bare `eth|` identity and changing that silently would be a real behavior\n * break for anyone already depending on it. Pass `{ scheme: 'eip712' }` to correctly resolve\n * a registered `client|` alias instead, for `RequestTrade`/`AddLiquidity`/`RemoveLiquidity`/\n * `CollectPositionFees` (`EIP712_CAPABLE_METHODS`) — `CreatePool` and any other method still\n * falls back to `personal_sign` even in `'eip712'` mode, since its EIP-712 signing is a\n * separate, unsolved chain-side problem.\n *\n * `eip712DomainName` is the EIP-712 domain name every typed-data signature carries (the\n * `'eip712'` scheme only; `personal_sign` has no domain): the deployment's own\n * (`GALA_CHAIN_ENVIRONMENTS[env].eip712DomainName`), `ethereum` when absent.\n *\n * @example\n * ```typescript\n * const signer = new BrowserWalletSigner(window.ethereum, '0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n * @example\n * ```typescript\n * // Correctly resolves a registered client| alias instead of the bare eth| address.\n * const signer = new BrowserWalletSigner(window.ethereum, walletAddress, { scheme: 'eip712' });\n * ```\n * @example\n * ```typescript\n * // The stage chain refuses any EIP-712 domain name but its own.\n * const signer = new BrowserWalletSigner(window.ethereum, walletAddress, {\n * scheme: 'eip712',\n * eip712DomainName: GALA_CHAIN_ENVIRONMENTS.stage.eip712DomainName,\n * });\n * ```\n */\n constructor(\n private readonly provider: BrowserWalletProvider,\n walletAddress: string,\n options: { scheme?: 'personal-sign' | 'eip712'; eip712DomainName?: string | undefined } = {},\n ) {\n this.walletAddress = normalizeEthereumAccount(walletAddress, false);\n this.scheme = options.scheme ?? 'personal-sign';\n this.eip712DomainName = options.eip712DomainName;\n }\n\n /** The selected `0x` Ethereum account every signature is requested for. */\n public readonly walletAddress: string;\n private readonly scheme: 'personal-sign' | 'eip712';\n private readonly eip712DomainName: string | undefined;\n\n /**\n * Signs the DTO with `eth_signTypedData_v4` (when constructed with `{ scheme: 'eip712' }` and\n * `methodName` is in `EIP712_CAPABLE_METHODS`) or the EIP-1193 `personal_sign` method\n * (otherwise — the default).\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n if (this.scheme === 'eip712' && EIP712_CAPABLE_METHODS.has(methodName)) {\n return signEIP712(this.provider, methodName, dto, this.walletAddress, this.eip712DomainName);\n }\n return personalSign(this.provider, dto, this.walletAddress);\n }\n}\n","/**\n * String-key signing entry points for apps that hold a private key only briefly (the Gala Wallet\n * extension reads its session key at sign time and must not keep it in a long-lived object).\n *\n * These are thin, byte-exact ports of the functions the wallet shipped (including the\n * fail-closed personal-sign payload resolver), re-expressed over the SDK's own primitives. Every\n * function takes the key as a string (`0x`-optional hex, or base64) or as bytes, normalizes it per\n * call, and zeroes the normalized copy before returning, so nothing in this module retains a key.\n * A JavaScript string cannot be wiped; the caller owns the lifetime of the string it passes in.\n */\nimport BigNumber from 'bignumber.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport {\n normalizePrivateKey,\n serialize,\n signPersonalMessage,\n signSerializedNative,\n} from './signing.js';\n\n/** A secp256k1 private key as a hex/base64 string or as raw 32 bytes. */\nexport type PrivateKeyInput = string | Uint8Array;\n\n/**\n * Runs `action` with a private normalized copy of the key, zeroed afterwards (also when `action`\n * throws). Bytes given by the caller are copied, never modified: the caller owns them.\n */\nexport function withPrivateKey<T>(privateKey: PrivateKeyInput, action: (key: Uint8Array) => T): T {\n const key = normalizePrivateKey(privateKey);\n try {\n return action(key);\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes with no\n * prefix and no envelope (wallet `signChainDtoNative`). The caller owns serialization, so the\n * bytes a user reviewed and the bytes signed cannot diverge.\n *\n * @returns 130 lowercase hex characters, `r || s || v` with `v` = `1b`/`1c`, no `0x`.\n */\nexport function signChainDtoNative(privateKey: PrivateKeyInput, serializedDto: string): string {\n return withPrivateKey(privateKey, (key) => signSerializedNative(key, serializedDto));\n}\n\n/**\n * The personal-sign hash primitive (wallet `signChainDtoHash`): keccak256(`prefix` + `message`),\n * both verbatim, with no further EIP-191 wrap. `message` must be the DTO's serialization WITHOUT\n * its `prefix` field; callers holding a dApp-supplied string go through `signChainDtoPersonalSign`,\n * which derives both inputs from it.\n */\nexport function signChainDtoHash(\n privateKey: PrivateKeyInput,\n prefix: string,\n message: string,\n): string {\n return withPrivateKey(privateKey, (key) => signPersonalMessage(key, prefix, message));\n}\n\nconst PERSONAL_SIGN_HEADER = String.fromCharCode(0x19) + 'Ethereum Signed Message:\\n';\nconst PERSONAL_SIGN_LENGTH_PATTERN = /^(?:0|[1-9][0-9]*)$/u;\n\n// A header with a body starting `{` can never collide with another EIP-191 message's hash, and\n// anything that is not a header (arbitrary bytes the user cannot see on an approval card) is\n// refused. The number is NOT required to equal the byte length: the chain hashes whatever prefix\n// the submitted DTO carries, and the swap backend's write guard rejects a mismatched header loudly.\nfunction isPersonalSignHeader(prefix: string): boolean {\n return (\n prefix.startsWith(PERSONAL_SIGN_HEADER) &&\n PERSONAL_SIGN_LENGTH_PATTERN.test(prefix.slice(PERSONAL_SIGN_HEADER.length))\n );\n}\n\n/**\n * Top-level fields that would make the chain (`getPayloadToSign`) or the swap backend's personal-sign\n * verifier hash something other than `prefix + serialize(dto minus prefix)`. An unsigned DTO from\n * a dApp never legitimately carries any of them, so they fail closed. Order is part of the error\n * message the wallet shows its user.\n */\nconst PERSONAL_SIGN_FORBIDDEN_FIELDS = [\n 'signature',\n 'multisig',\n 'trace',\n 'types',\n 'domain',\n 'stringsInstructions',\n] as const;\n\n/** What a `gala_signChainDto` personal-sign request hashes. */\nexport interface PersonalSignChainDtoPayload {\n /** The `prefix` the chain prepends: the DTO's own `prefix` field, or `''` when it has none. */\n prefix: string;\n /** The exact message hashed after `prefix`. */\n message: string;\n}\n\n/**\n * Derives what to hash for a `gala_signChainDto` personal-sign request from the exact string the\n * dApp sent (and the approval card displayed): wallet `resolvePersonalSignChainDtoPayload`.\n *\n * The dApp submits `{ ...dto, prefix, signature }`, which the chain recovers from\n * `keccak256(prefix + serialize(dto WITHOUT prefix))`. So when the string embeds a `prefix`\n * field, that field is removed and the remainder re-serialized; the prefix used is the dApp's own\n * value byte for byte. A string with no `prefix` field is hashed verbatim with an empty prefix\n * (chain-equivalent to a native signature of that exact string).\n *\n * Fails closed (throws `GalaSDKError` `PERSONAL_SIGN_NOT_JSON`, `PERSONAL_SIGN_NOT_OBJECT`,\n * `PERSONAL_SIGN_BAD_PREFIX`, `PERSONAL_SIGN_ENVELOPE_FIELDS` or `PERSONAL_SIGN_NOT_CANONICAL`) on:\n * malformed JSON; JSON that is not a plain object; a `prefix` that is not an EIP-191\n * \"Ethereum Signed Message\" header; any signing-envelope field (`signature`, `multisig`, `trace`,\n * `types`, `domain`, `stringsInstructions`); and a string that is not already the canonical\n * serialization of what it parses to (duplicate keys, lossy numbers, key-order tricks the card\n * would render differently). Stripping `prefix` is therefore the ONLY byte change between the\n * reviewed string and the signed message.\n */\nexport function resolvePersonalSignChainDtoPayload(data: string): PersonalSignChainDtoPayload {\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n throw new GalaSDKError('PERSONAL_SIGN_NOT_JSON', {});\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new GalaSDKError('PERSONAL_SIGN_NOT_OBJECT', {});\n }\n const dto = parsed as Record<string, unknown>;\n if (!Object.prototype.hasOwnProperty.call(dto, 'prefix')) {\n return { prefix: '', message: data };\n }\n\n const { prefix, ...withoutPrefix } = dto;\n if (typeof prefix !== 'string' || !isPersonalSignHeader(prefix)) {\n throw new GalaSDKError('PERSONAL_SIGN_BAD_PREFIX', {});\n }\n const forbidden = PERSONAL_SIGN_FORBIDDEN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(withoutPrefix, field),\n );\n if (forbidden.length > 0) {\n throw new GalaSDKError('PERSONAL_SIGN_ENVELOPE_FIELDS', { fields: forbidden.join(', ') });\n }\n if (serialize(dto) !== data) {\n throw new GalaSDKError('PERSONAL_SIGN_NOT_CANONICAL', {});\n }\n return { prefix, message: serialize(withoutPrefix) };\n}\n\n/**\n * Signs a GalaChain personal-sign scheme DTO from the exact string a dApp sent through\n * `gala_signChainDto` (wallet `signChainDtoPersonalSign`). See\n * `resolvePersonalSignChainDtoPayload` for what is signed and what is refused; the signature\n * recovers, under the chain's `getPayloadToSign`, to this key for the DTO the dApp submits with\n * its `prefix`, and equals a `personal_sign` of the bare body when that prefix is the EIP-191\n * header of the bare body's byte length.\n *\n * @throws GalaSDKError (`PERSONAL_SIGN_*`, see `resolvePersonalSignChainDtoPayload`) before any\n * signing when the input is refused.\n */\nexport function signChainDtoPersonalSign(privateKey: PrivateKeyInput, data: string): string {\n const { prefix, message } = resolvePersonalSignChainDtoPayload(data);\n return signChainDtoHash(privateKey, prefix, message);\n}\n\n/**\n * Raw object signing (wallet `signObject`), used for transfers, bridge and fee-dry-run DTOs the\n * wallet signs itself. Removes ONLY `signature`, signs `keccak256(serialize(rest))` natively\n * (no `prefix` handling, and `trace` / `multisig` stay in the signed bytes, unlike\n * `signNative`), and returns `{ signature, ...rest }` with the signature as the FIRST key, exactly\n * like the wallet. Callers that must not sign extra fields strip them first.\n */\nexport function signRawObject(\n privateKey: PrivateKeyInput,\n obj: Record<string, unknown>,\n): { signature: string } & Record<string, unknown> {\n const rest = { ...obj };\n delete rest['signature'];\n return {\n signature: signChainDtoNative(privateKey, serialize(rest)),\n ...rest,\n };\n}\n\n/**\n * Drops the `EIP712Domain` entry from a dApp-supplied types map (a typed-data encoder derives the\n * domain type itself and rejects an explicit one). The order of the remaining types is preserved.\n */\nexport function stripEip712DomainType<T>(types: Record<string, T>): Record<string, T> {\n const stripped: Record<string, T> = {};\n for (const typeName of Object.keys(types)) {\n if (typeName !== 'EIP712Domain') stripped[typeName] = types[typeName] as T;\n }\n return stripped;\n}\n\n/**\n * `collection$category$type$additionalKey` for a token-class object (wallet `decodeTokenData`).\n * Lenient on purpose: any missing or non-string part becomes `''`, so a display layer never\n * throws on odd input.\n */\nexport function tokenClassDollarKey(token: Record<string, unknown> | null | undefined): string {\n const part = (field: string): string => {\n const value = token?.[field];\n return typeof value === 'string' ? value : '';\n };\n return `${part('collection')}$${part('category')}$${part('type')}$${part('additionalKey')}`;\n}\n\n/**\n * A quantity in the form GalaChain's `IsBigNumber` validator accepts: FIXED notation, no leading\n * zeros, no trailing decimal zeros (`BigNumber#toFixed()`; never `toString()`, which turns\n * `0.00000001` into `1e-8`, and never a JS number in between).\n *\n * @throws GalaSDKError (`INVALID_DECIMAL`) for a value that is not a finite number. The wallet's\n * `cleanNumber` returned the string `'NaN'` there; signing that text can only fail on chain.\n */\nexport function canonicalDecimalString(value: string | number): string {\n let parsed = new BigNumber(Number.NaN);\n try {\n parsed = new BigNumber(value);\n } catch {\n // BigNumber throws instead of returning NaN when its DEBUG flag is on; both mean \"invalid\".\n }\n if (!parsed.isFinite()) {\n throw new GalaSDKError('INVALID_DECIMAL', { value: String(value) });\n }\n return parsed.toFixed();\n}\n","/**\n * EIP-712 (`eth_signTypedData_v4`) hashing and signing for ARBITRARY dApp typed data, built on the\n * SDK's own primitives (`@noble/curves`, `@noble/hashes`) so a wallet can sign a dApp's typed-data\n * approval without ethers. It replaces the wallet's `new ethers.Wallet(key).signTypedData(...)`\n * and is pinned to it: the golden suite reproduces every fixture signature exactly and a seeded\n * differential fuzz compares the digest and signature with ethers for every supported type.\n *\n * Compared with ethers this encoder is deliberately STRICTER (it fails closed rather than coerce):\n * `bool` accepts only a boolean, numbers accept only safe integers / decimal or `0x` strings,\n * strings must be well-formed UTF-16, struct values must be objects whose fields are their own\n * properties, and every struct, field and type name must be a plain identifier. Anything ethers\n * accepts that is NOT in that set is refused here instead of being signed in a different shape\n * from what a user reviewed.\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { hasValidEip55Casing } from './eth_address.js';\nimport { signHash } from './signing.js';\nimport { withPrivateKey, type PrivateKeyInput } from './chain_dto_signing.js';\n\n/** A typed-data payload as `eth_signTypedData_v4` carries it, minus `primaryType` (it is inferred). */\nexport interface TypedDataPayload {\n domain: Record<string, unknown>;\n /** Struct definitions WITHOUT `EIP712Domain` (see `stripEip712DomainType`). */\n types: Record<string, readonly unknown[]>;\n message: Record<string, unknown>;\n}\n\ninterface TypedField {\n name: string;\n type: string;\n}\n\nconst textEncoder = new TextEncoder();\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;\nconst TYPE_SYNTAX = /^([A-Za-z_$][A-Za-z0-9_$]*)((?:\\[(?:0|[1-9][0-9]*)?\\])*)$/u;\nconst BIGINT_DECIMAL = /^-?[0-9]+$/u;\nconst BIGINT_HEX = /^-?0x[0-9a-fA-F]+$/u;\n\n/** The EIP-712 domain members and their types, in the order ethers (and the spec) hash them. */\nconst DOMAIN_FIELDS: readonly TypedField[] = [\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n];\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction bigintToWord(value: bigint): Uint8Array {\n const word = new Uint8Array(32);\n // Every caller has bounds-checked `value` against its Solidity type, so it fits in 256 bits.\n let rest = value < 0n ? value + (1n << 256n) : value;\n for (let index = 31; index >= 0; index -= 1) {\n word[index] = Number(rest & 0xffn);\n rest >>= 8n;\n }\n return word;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const body = hex.slice(2);\n const out = new Uint8Array(body.length / 2);\n for (let index = 0; index < out.length; index += 1) {\n out[index] = parseInt(body.slice(index * 2, index * 2 + 2), 16);\n }\n return out;\n}\n\nfunction toBytes(value: unknown, what: string): Uint8Array {\n if (value instanceof Uint8Array) return value;\n if (typeof value === 'string' && /^0x(?:[0-9a-fA-F]{2})*$/u.test(value)) return hexToBytes(value);\n throw new GalaSDKError('TYPED_DATA_NOT_HEX_BYTES', { what });\n}\n\nfunction toBigInt(value: unknown, what: string): bigint {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value))\n throw new GalaSDKError('TYPED_DATA_NOT_SAFE_INTEGER', { what });\n return BigInt(value);\n }\n if (typeof value === 'string') {\n if (BIGINT_DECIMAL.test(value)) return BigInt(value);\n if (BIGINT_HEX.test(value)) {\n return value.startsWith('-') ? -BigInt(value.slice(1)) : BigInt(value);\n }\n }\n throw new GalaSDKError('TYPED_DATA_NOT_INTEGER', { what });\n}\n\nfunction utf8(value: unknown, what: string): Uint8Array {\n if (typeof value !== 'string') throw new GalaSDKError('TYPED_DATA_NOT_STRING', { what });\n for (let index = 0; index < value.length; index += 1) {\n const unit = value.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n }\n return textEncoder.encode(value);\n}\n\n/** EIP-55: a mixed-case address must carry the right checksum; all-lower / all-upper is accepted. */\nfunction addressBytes(value: unknown): Uint8Array {\n if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{40}$/u.test(value)) {\n throw new GalaSDKError('TYPED_DATA_BAD_ADDRESS', {});\n }\n if (!hasValidEip55Casing(value.slice(2))) {\n throw new GalaSDKError('TYPED_DATA_BAD_CHECKSUM', {});\n }\n return hexToBytes(value);\n}\n\ntype LeafEncoder = (value: unknown) => Uint8Array;\n\n/** The encoder for a non-struct, non-array type, or undefined when `base` is not one. */\nfunction leafEncoder(base: string): LeafEncoder | undefined {\n if (base === 'string') return (value) => keccak_256(utf8(value, 'string'));\n if (base === 'bytes') return (value) => keccak_256(toBytes(value, 'bytes'));\n if (base === 'bool') {\n return (value) => {\n if (typeof value !== 'boolean') throw new GalaSDKError('TYPED_DATA_NOT_BOOLEAN', {});\n return bigintToWord(value ? 1n : 0n);\n };\n }\n if (base === 'address') {\n return (value) => concat([new Uint8Array(12), addressBytes(value)]);\n }\n const fixed = /^bytes([1-9][0-9]?)$/u.exec(base);\n if (fixed !== null) {\n const width = Number(fixed[1]);\n // The pattern above admits no leading zero, so `String(width)` is always the digits written.\n if (width > 32) return undefined;\n return (value) => {\n const bytes = toBytes(value, base);\n if (bytes.length !== width) {\n throw new GalaSDKError('TYPED_DATA_BYTES_LENGTH', { type: base, width });\n }\n return concat([bytes, new Uint8Array(32 - width)]);\n };\n }\n const integer = /^(u?)int([1-9][0-9]*)$/u.exec(base);\n if (integer !== null) {\n const width = Number(integer[2]);\n if (width % 8 !== 0 || width > 256 || String(width) !== integer[2]) return undefined;\n const signed = integer[1] === '';\n const lower = signed ? -(1n << BigInt(width - 1)) : 0n;\n const upper = signed ? (1n << BigInt(width - 1)) - 1n : (1n << BigInt(width)) - 1n;\n return (value) => {\n const number = toBigInt(value, base);\n if (number < lower || number > upper) {\n throw new GalaSDKError('TYPED_DATA_OUT_OF_BOUNDS', { type: base });\n }\n return bigintToWord(number);\n };\n }\n return undefined;\n}\n\ninterface ParsedType {\n base: string;\n /** Array suffixes outermost-last, e.g. `uint256[2][]` is `[2, -1]` (-1 = dynamic). */\n dimensions: number[];\n}\n\nfunction parseType(type: string): ParsedType {\n const match = TYPE_SYNTAX.exec(type);\n if (match === null) throw new GalaSDKError('TYPED_DATA_UNSUPPORTED_TYPE', { type });\n // Group 2 of TYPE_SYNTAX is `(...)*` around the whole suffix run, so it always participates.\n const dimensions = [...(match[2] as string).matchAll(/\\[([0-9]*)\\]/gu)].map((dimension) =>\n dimension[1] === '' ? -1 : Number(dimension[1]),\n );\n return { base: match[1] as string, dimensions };\n}\n\nfunction parseFields(typeName: string, rawFields: readonly unknown[]): TypedField[] {\n if (!Array.isArray(rawFields)) throw new GalaSDKError('TYPED_DATA_FIELDS_NOT_LIST', { typeName });\n const seen = new Set<string>();\n return rawFields.map((raw: unknown) => {\n const field = raw as { name?: unknown; type?: unknown } | null;\n if (typeof field?.name !== 'string' || typeof field.type !== 'string') {\n throw new GalaSDKError('TYPED_DATA_FIELD_MALFORMED', { typeName });\n }\n if (!IDENTIFIER.test(field.name)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_FIELD_NAME', { name: field.name });\n }\n if (seen.has(field.name)) {\n throw new GalaSDKError('TYPED_DATA_DUPLICATE_FIELD', { name: field.name, typeName });\n }\n seen.add(field.name);\n // A bare `int` / `uint` is the 256-bit type and is hashed as `int256` / `uint256`, like ethers.\n const parsed = parseType(field.type);\n const base =\n parsed.base === 'uint' || parsed.base === 'int' ? `${parsed.base}256` : parsed.base;\n return { name: field.name, type: base + field.type.slice(parsed.base.length) };\n });\n}\n\ninterface StructEncoder {\n primaryType: string;\n hashStruct: (typeName: string, value: unknown) => Uint8Array;\n}\n\n/**\n * Builds the struct encoder for a set of type definitions: validates the type graph (unknown or\n * circular references, duplicate fields) and infers the primary type as the single type no other\n * type references, exactly like ethers' `TypedDataEncoder`.\n */\nfunction createStructEncoder(rawTypes: Record<string, readonly unknown[]>): StructEncoder {\n const names = Object.keys(rawTypes);\n const fields = new Map<string, TypedField[]>();\n for (const name of names) {\n if (!IDENTIFIER.test(name)) throw new GalaSDKError('TYPED_DATA_INVALID_TYPE_NAME', { name });\n fields.set(name, parseFields(name, rawTypes[name] as readonly unknown[]));\n }\n\n const children = new Map<string, Set<string>>();\n const parents = new Map<string, Set<string>>();\n for (const name of names) {\n children.set(name, new Set());\n parents.set(name, new Set());\n }\n for (const [name, list] of fields) {\n for (const field of list) {\n const { base } = parseType(field.type);\n if (base === name) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (leafEncoder(base) !== undefined) continue;\n if (!fields.has(base)) {\n throw new GalaSDKError('TYPED_DATA_UNKNOWN_FIELD_TYPE', { type: base, typeName: name });\n }\n children.get(name)?.add(base);\n parents.get(base)?.add(name);\n }\n }\n\n const roots = names.filter((name) => parents.get(name)?.size === 0);\n if (roots.length === 0) throw new GalaSDKError('TYPED_DATA_NO_PRIMARY_TYPE', {});\n if (roots.length > 1) {\n throw new GalaSDKError('TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE', { roots: roots.join(', ') });\n }\n const primaryType = roots[0] as string;\n\n const visiting = new Set<string>();\n const checked = new Set<string>();\n const checkCircular = (name: string): void => {\n if (visiting.has(name)) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (checked.has(name)) return;\n visiting.add(name);\n // `children` holds an entry for every name, and `name` is always one of them.\n for (const child of children.get(name) as Set<string>) checkCircular(child);\n visiting.delete(name);\n checked.add(name);\n };\n checkCircular(primaryType);\n\n const dependencies = (name: string, found: Set<string>): Set<string> => {\n for (const child of children.get(name) as Set<string>) {\n if (!found.has(child)) {\n found.add(child);\n dependencies(child, found);\n }\n }\n return found;\n };\n const encodeOne = (name: string): string =>\n `${name}(${(fields.get(name) as TypedField[]).map((field) => `${field.type} ${field.name}`).join(',')})`;\n const typeHashes = new Map<string, Uint8Array>();\n for (const name of names) {\n const sorted = [...dependencies(name, new Set())].filter((dep) => dep !== name).sort();\n typeHashes.set(name, keccak_256(textEncoder.encode([name, ...sorted].map(encodeOne).join(''))));\n }\n\n const encodeValue = (parsed: ParsedType, value: unknown, depth: number): Uint8Array => {\n // The LAST bracket written is the outermost array: `uint8[][2]` is two `uint8[]`.\n const dimension = parsed.dimensions[parsed.dimensions.length - 1 - depth];\n if (dimension !== undefined) {\n if (!Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_EXPECTED', { type: parsed.base });\n }\n if (dimension !== -1 && dimension !== value.length) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_LENGTH_MISMATCH', {});\n }\n return keccak_256(concat(value.map((item) => encodeValue(parsed, item, depth + 1))));\n }\n const leaf = leafEncoder(parsed.base);\n if (leaf !== undefined) return leaf(value);\n return hashStruct(parsed.base, value);\n };\n\n function hashStruct(typeName: string, value: unknown): Uint8Array {\n // createStructEncoder has already validated every struct name this is called with (the\n // primary type, the domain type, and each field base that is not a leaf type).\n const list = fields.get(typeName) as TypedField[];\n const typeHash = typeHashes.get(typeName) as Uint8Array;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_STRUCT_NOT_OBJECT', { typeName });\n }\n const record = value as Record<string, unknown>;\n const words = list.map((field) => {\n if (!Object.prototype.hasOwnProperty.call(record, field.name)) {\n throw new GalaSDKError('TYPED_DATA_MISSING_FIELD', { typeName, field: field.name });\n }\n // Struct-valued fields are encoded to their 32-byte struct hash by encodeValue.\n return encodeValue(parseType(field.type), record[field.name], 0);\n });\n return keccak_256(concat([typeHash, ...words]));\n }\n\n return { primaryType, hashStruct };\n}\n\nfunction hashDomain(domain: Record<string, unknown>): Uint8Array {\n if (domain === null || typeof domain !== 'object' || Array.isArray(domain)) {\n throw new GalaSDKError('TYPED_DATA_DOMAIN_NOT_OBJECT', {});\n }\n for (const key of Object.keys(domain)) {\n if (!DOMAIN_FIELDS.some((field) => field.name === key)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_DOMAIN_KEY', { key: JSON.stringify(key) });\n }\n }\n const present = DOMAIN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(domain, field.name),\n );\n const encoder = createStructEncoder({ EIP712Domain: present });\n return encoder.hashStruct('EIP712Domain', domain);\n}\n\n/**\n * The EIP-712 digest `keccak256(0x1901 || domainSeparator || hashStruct(primaryType, message))`\n * that a wallet signs for `eth_signTypedData_v4`. The primary type is inferred, as ethers does.\n *\n * @throws GalaSDKError (`TYPED_DATA_*`) for any type graph or value it cannot encode\n * exactly (see the module note on strictness).\n */\nexport function hashTypedData(payload: TypedDataPayload): Uint8Array {\n const domainHash = hashDomain(payload.domain);\n const encoder = createStructEncoder(payload.types);\n const structHash = encoder.hashStruct(encoder.primaryType, payload.message);\n return keccak_256(concat([Uint8Array.of(0x19, 0x01), domainHash, structHash]));\n}\n\n/**\n * Signs a dApp's EIP-712 typed-data approval (the wallet's `signTypedMessage` path), replacing\n * `new ethers.Wallet(key).signTypedData(domain, types, message)`. `types` must already have\n * `EIP712Domain` removed (`stripEip712DomainType`).\n *\n * @returns `0x` + r + s + v with `v` = `0x1b`/`0x1c` (27/28): ethers' serialized signature form,\n * recoverable with `verifyTypedData` / `eth_signTypedData_v4` verifiers. Rejects (never throws\n * synchronously) on invalid input.\n */\nexport async function signTypedDataPayload(\n privateKey: PrivateKeyInput,\n payload: TypedDataPayload,\n): Promise<string> {\n const digest = hashTypedData(payload);\n return withPrivateKey(privateKey, (key) => `0x${signHash(key, digest)}`);\n}\n","/**\n * The chain's operation ids for the GalaChain contracts the gateway routes, from the gateway's\n * `dtoOperationMap` (the `dtoOperation` / API path table of the GalaChain platform team,\n * 2026-10-27). The chain refuses a signed DTO whose `dtoOperation` is not exactly the operation it\n * is called through (\"The dto was signed to call X operation, but the current operation is Y\"), so\n * the URL a write is POSTed to and the `dtoOperation` it carries both come from this one table and\n * can never disagree.\n *\n * `dtoOperation` is a SIGNED field: it is part of the DTO before the signer sees it, never added by\n * a signer or after the signature.\n */\n\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\n\n/** `<channel>/<contract route>`: the path after `/api/` (or `/v1/chain/`) a contract is served at. */\nexport const CHAIN_CONTRACT_OPERATION_PREFIXES = {\n 'asset/public-key-contract': 'asset-channel_basic-asset_PublicKeyContract',\n 'asset/token-contract': 'asset-channel_basic-asset_GalaChainToken',\n 'asset/fee-contract': 'asset-channel_basic-asset_GalaChainFee',\n 'asset/launchpad-contract': 'asset-channel_basic-asset_Launchpad',\n 'asset/dexv3-contract': 'asset-channel_basic-asset_DexV3Contract',\n 'asset/dex-contract': 'asset-channel_basic-asset_GalaChainDex',\n 'asset/registrar-contract': 'asset-channel_basic-asset_RegistrarContract',\n 'asset/staking-contract': 'asset-channel_basic-asset_StakingContract',\n 'asset/wallet-attributes-contract': 'asset-channel_basic-asset_WalletAttributesContract',\n // The gateway's table lists the bridge contract here. On stage (2026-11-02) a `RequestTokenBridgeOut` is refused\n // under it: the chain's operation for that call is the TOKEN contract's (`asset/token-contract`). `BridgeTokenOut`\n // on `/asset/bridge-contract` IS `asset-channel_bridge-chaincode_BridgeContract:BridgeTokenOut` (seen live on stage;\n // GalaConnect signs it, this SDK does not). The grants embedded in a `BridgeTokenOut` sign\n // `asset-channel_bridge-chaincode_GalaChainToken:GrantAllowance`, which is NOT in the platform CSV or this table\n // (seen live on stage, signed by GalaConnect).\n 'asset/bridge-contract': 'asset-channel_bridge-chaincode_BridgeContract',\n 'asset/bridge-public-key-contract': 'asset-channel_bridge-chaincode_PublicKeyContract',\n 'asset/alm-contract': 'asset-channel_basic-asset_ALMContract',\n 'spidertanks/contract': 'spidertanks-channel_spidertanks_SpiderTanks',\n 'music/public-key-contract': 'music_music_PublicKeyContract',\n 'music/music-contract': 'music_music_GalaMusic',\n 'music/token-contract': 'music_music_GalaChainToken',\n 'pokergo/pokergo-contract': 'pokergo_pokergo_PokerGo',\n 'pokergo/public-key-contract': 'pokergo_pokergo_PublicKeyContract',\n 'pokergo/token-contract': 'pokergo_pokergo_GalaChainToken',\n 'championsarena/public-key-contract': 'championsarena_championsarena_PublicKeyContract',\n 'championsarena/champions-arena': 'championsarena_championsarena_ChampionsArenaContract',\n 'championsarena/token-contract': 'championsarena_championsarena_GalaChainToken',\n 'superior/public-key-contract': 'superior_superior_PublicKeyContract',\n 'superior/token-contract': 'superior_superior_GalaChainToken',\n 'superior/superior': 'superior_superior_Product',\n 'legacy/public-key-contract': 'legacy_legacy_PublicKeyContract',\n 'legacy/token-contract': 'legacy_legacy_GalaChainToken',\n 'legacy/legacy': 'legacy_legacy_Legacy',\n 'eternalparadox/public-key-contract': 'eternalparadox_eternalparadox_PublicKeyContract',\n 'eternalparadox/token-contract': 'eternalparadox_eternalparadox_GalaChainToken',\n 'eternalparadox/eternalparadox': 'eternalparadox_eternalparadox_EternalParadox',\n 'echoesofempire/public-key-contract': 'echoesofempire_echoesofempire_PublicKeyContract',\n 'echoesofempire/token-contract': 'echoesofempire_echoesofempire_GalaChainToken',\n 'echoesofempire/echoesofempire-contract': 'echoesofempire_echoesofempire_EchoesOfEmpire',\n 'node/public-key-contract': 'node_node_PublicKeyContract',\n 'node/token-contract': 'node_node_GalaChainToken',\n 'node/node-contract': 'node_node_Product',\n 'townstar/product-contract': 'townstar_townstar_TownStar',\n 'townstar/token-contract': 'townstar_townstar_GalaChainToken',\n 'townstar/public-key-contract': 'townstar_townstar_PublicKeyContract',\n 'mirandus/public-key-contract': 'mirandus_mirandus_PublicKeyContract',\n 'mirandus/token-contract': 'mirandus_mirandus_GalaChainToken',\n 'mirandus/mirandus-contract': 'mirandus_mirandus_Product',\n 'galafilm/public-key-contract': 'galafilm_galafilm_PublicKeyContract',\n 'galafilm/token-contract': 'galafilm_galafilm_GalaChainToken',\n 'galafilm/galafilm-contract': 'galafilm_galafilm_Product',\n 'lastexpedition/public-key-contract': 'lastexpedition_lastexpedition_PublicKeyContract',\n 'lastexpedition/token-contract': 'lastexpedition_lastexpedition_GalaChainToken',\n 'lastexpedition/lastexpedition-contract': 'lastexpedition_lastexpedition_Product',\n 'legendsreborn/public-key-contract': 'legendsreborn_legendsreborn_PublicKeyContract',\n 'legendsreborn/token-contract': 'legendsreborn_legendsreborn_GalaChainToken',\n 'legendsreborn/legendsreborn-contract': 'legendsreborn_legendsreborn_Product',\n 'thewalkingdeadempires/public-key-contract':\n 'thewalkingdeadempires_thewalkingdeadempires_PublicKeyContract',\n 'thewalkingdeadempires/token-contract':\n 'thewalkingdeadempires_thewalkingdeadempires_GalaChainToken',\n 'thewalkingdeadempires/thewalkingdeadempires-contract':\n 'thewalkingdeadempires_thewalkingdeadempires_Product',\n 'vox/public-key-contract': 'vox_vox_PublicKeyContract',\n 'vox/token-contract': 'vox_vox_GalaChainToken',\n 'vox/auction-contract': 'vox_vox_AuctionContract',\n 'vox/phase-contract': 'vox_vox_PhaseContract',\n 'vox/vox-contract': 'vox_vox_VOXTokenContract',\n 'vox/resources-contract': 'vox_vox_VOXResourceToken',\n} as const;\n\n/** An API path of a GalaChain contract (`asset/token-contract`, `asset/dex-contract`, ...). */\nexport type ChainContractPath = keyof typeof CHAIN_CONTRACT_OPERATION_PREFIXES;\n\n/** The `dtoOperation` of `method` on the contract served at `contractPath`. */\nexport function dtoOperationOf(contractPath: ChainContractPath, method: string): string {\n return `${CHAIN_CONTRACT_OPERATION_PREFIXES[contractPath]}:${method}`;\n}\n\n/**\n * `dto` with its `dtoOperation` set for `method` on `contractPath`. A DTO that already names a\n * different operation is refused: it was built for another call, and sending it would be rejected\n * by the chain after the signer had already signed it.\n *\n * @throws GalaSDKError SIGNING_FAILED when `dto.dtoOperation` is set and is not the operation of this call.\n */\nexport function withDtoOperation<T extends Record<string, unknown>>(\n contractPath: ChainContractPath,\n method: string,\n dto: T,\n): T & { readonly dtoOperation: string } {\n const dtoOperation = dtoOperationOf(contractPath, method);\n const present = dto['dtoOperation'];\n if (present !== undefined && present !== dtoOperation) {\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n { method, reason: 'failed' },\n { cause: { dtoOperation: present, expected: dtoOperation } },\n );\n }\n return { ...dto, dtoOperation };\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","import { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport type { GalaChainSigner, SignedDto } from '../classes/signers.js';\nimport { withDtoOperation, type ChainContractPath } from './dto_operation.js';\nimport { isWalletUserRejection, walletDeclineCode } from './wallet_rejection.js';\n\n/**\n * The boundary of \"nothing was sent\". Every place where an SDK hands control to code the APP\n * supplied BEFORE the request leaves (the signer here; a product SDK's token resolver) goes through\n * such a wrapper, so a failure of that code reaches the caller as a catalogued, pre-send SDK error\n * with the original as `cause`, never as a bare value the SDK cannot classify. An SDK error thrown\n * by that code is already catalogued and passes through untouched. Nothing here is used after the\n * request has been sent: an app's own rejection AFTER send stays what it is, because the SDK\n * cannot know what the server did with the write.\n */\n\n/**\n * Signs a DTO with the app's signer, after setting its `dtoOperation` to the operation of `method`\n * on the contract at `contractPath` (the chain refuses a DTO signed for another operation). Whatever the signer throws that is not already an SDK error\n * (a locked wallet, an unreachable extension, a wallet that declined) is `SIGNING_FAILED`\n * (`reason` `user_rejected` or `failed`, the original as `cause`), and a signer that returns\n * something other than an object is `SIGNING_FAILED` too: both are pre-send, so a retry is safe.\n * An SDK error of ANY product (every one is a `GalaSDKError`) passes through as it is.\n *\n * @throws GalaSDKError SIGNING_FAILED, or the SDK error the signer itself threw.\n */\nexport async function signPreSend<T extends Record<string, unknown>>(\n signer: GalaChainSigner,\n contractPath: ChainContractPath,\n method: string,\n dto: T,\n): Promise<SignedDto<T>> {\n let signed: SignedDto<T>;\n try {\n signed = await signer.signObject(method, withDtoOperation(contractPath, method, dto));\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n const reason = isWalletUserRejection(cause) ? 'user_rejected' : 'failed';\n throw new GalaSDKError(\n 'SIGNING_FAILED',\n { method, reason },\n { cause, walletCode: walletDeclineCode(cause) },\n );\n }\n if (typeof signed !== 'object' || signed === null) {\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause: signed });\n }\n return signed;\n}\n","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.4';\n","import type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { GalaSDKError, isGalaError, parseJson } from '../classes/gala_sdk_error.js';\nimport { GALA_CORE_SDK_VERSION } from '../version.js';\n\n/**\n * Arms the abort timer for a request. `Infinity` means \"never time out\": `setTimeout` would turn\n * it into 1 ms, so no timer is armed at all. Returns a function that disarms it.\n */\nexport function armTimeout(controller: AbortController, timeoutMs: number): () => void {\n if (timeoutMs === Infinity) return () => undefined;\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return () => clearTimeout(timer);\n}\n\n/**\n * Validates a request timeout in milliseconds: a positive finite number, or `Infinity` for none.\n *\n * @throws GalaSDKError `INVALID_TIMEOUT` (`params.field` = `name`) otherwise.\n */\nexport function validateTimeoutMs(timeoutMs: number, name: string): number {\n if (timeoutMs === Infinity || (Number.isFinite(timeoutMs) && timeoutMs > 0)) return timeoutMs;\n throw new GalaSDKError('INVALID_TIMEOUT', { field: name, value: timeoutMs });\n}\n\nconst READABLE_QUERY_SAFE = /[A-Za-z0-9\\-._~!'()*$|:,]/u;\n\nfunction encodeReadable(text: string): string {\n let out = '';\n for (const char of text) {\n if (char === ' ') out += '+';\n else if (READABLE_QUERY_SAFE.test(char)) out += char;\n else out += encodeScalar(char);\n }\n return out;\n}\n\n/** Percent-encodes one code point; a lone surrogate becomes U+FFFD, as `URLSearchParams` does. */\nfunction encodeScalar(char: string): string {\n try {\n return encodeURIComponent(char);\n } catch {\n return '%EF%BF%BD';\n }\n}\n\n/** Serializes GET parameters, in insertion order, in the encoding the wire options select. */\nexport function buildQueryString(\n params: Record<string, string>,\n encoding: WireOptions['queryEncoding'] = 'standard',\n): string {\n if (encoding === 'readable') {\n return Object.entries(params)\n .map(([key, value]) => `${encodeReadable(key)}=${encodeReadable(value)}`)\n .join('&');\n }\n return new URLSearchParams(params).toString();\n}\n\n/** What an SDK request adds to the headers the wire options describe. */\nexport interface RequestHeaderParts {\n /** The request carries a JSON body: `Content-Type: application/json` unless `wire.headers` sets one. */\n json?: boolean | undefined;\n /** Headers the SDK sends unless `wire.headers` replaces them (for example `Accept`). */\n defaults?: Record<string, string> | undefined;\n /**\n * Headers that carry the request's meaning (`X-Wallet-Address`, `X-Shadow`). They come last and\n * replace a same-named `wire.headers` entry, so an app's static headers can never re-attribute\n * or un-shadow a write.\n */\n fixed?: Record<string, string> | undefined;\n}\n\n/**\n * The request headers for ANY SDK request, GET or POST, from one place so the wire options reach\n * every request alike. Order, which is the order the requestor sees them in: `User-Agent`\n * (`wire.userAgent`, default `GalaChain-SDK/<version>`, `false` omits it), `parts.defaults`,\n * `wire.headers`, `Content-Type` (JSON bodies only), `parts.fixed`. A later entry replaces an\n * earlier one of the same name regardless of case, so a header is never sent twice.\n */\nexport function buildRequestHeaders(\n wire: WireOptions | undefined,\n parts: RequestHeaderParts = {},\n): Record<string, string> {\n const entries = new Map<string, [name: string, value: string]>();\n const put = (headers: Record<string, string> | undefined, last = false): void => {\n for (const [name, value] of Object.entries(headers ?? {})) {\n // A fixed header leaves any earlier same-named entry behind, so it also keeps its place at the end.\n if (last) entries.delete(name.toLowerCase());\n entries.set(name.toLowerCase(), [name, value]);\n }\n };\n if (wire?.userAgent !== false) {\n put({ 'User-Agent': wire?.userAgent ?? `GalaChain-SDK/${GALA_CORE_SDK_VERSION}` });\n }\n put(parts.defaults);\n put(wire?.headers);\n if (parts.json === true && !entries.has('content-type')) {\n put({ 'Content-Type': 'application/json' });\n }\n put(parts.fixed, true);\n return Object.fromEntries(entries.values());\n}\n\n/**\n * The default requestor: the global `fetch`, with a failure before any answer (offline, DNS,\n * CORS) coded as `TRANSPORT_ERROR` and the original error kept as `cause`. An aborted request is\n * left to {@link requestWithTimeout}, which knows whether the timeout or the caller aborted it.\n * A requestor the app supplies is not wrapped: its rejection reaches the caller unchanged.\n */\nexport const fetchRequestor: HttpRequestor = async (url, init) => {\n try {\n return await fetch(url, init);\n } catch (error: unknown) {\n if (init?.signal?.aborted === true) throw error;\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause: error });\n }\n};\n\n/** What a request is, for the failures the transport raises itself (see {@link requestWithTimeout}). */\nexport interface RequestKind {\n /** `false` for a read: nothing it sends is applied, so its failures say `write: false`. */\n write: boolean;\n}\n\n/**\n * Sends one request through `requestor`, aborting it after `timeoutMs` (`REQUEST_TIMEOUT`). The\n * caller's own abort passes through as it is. `kind: { write: false }` marks a read: its\n * `REQUEST_TIMEOUT`, and a `TRANSPORT_ERROR` of the default requestors (which cannot tell a read\n * from a write), then say `write: false`. Without it they are judged as a write's (fail-closed),\n * which is what a write's transport needs before it decides what an unanswered write means.\n */\nexport async function requestWithTimeout(\n requestor: HttpRequestor,\n url: string,\n options: RequestInit,\n timeoutMs: number,\n kind?: RequestKind,\n): Promise<HTTPResponse> {\n const controller = new AbortController();\n const disarm = armTimeout(controller, timeoutMs);\n const externalSignal = options.signal;\n const abortFromCaller = (): void => controller.abort();\n externalSignal?.addEventListener('abort', abortFromCaller, { once: true });\n const read = kind?.write === false;\n try {\n return await requestor(url, { ...options, signal: controller.signal });\n } catch (error: unknown) {\n // The caller's own abort is theirs: it passes through as the abort it is, never as a timeout.\n if (externalSignal?.aborted === true) throw error;\n if (controller.signal.aborted) {\n throw new GalaSDKError(\n 'REQUEST_TIMEOUT',\n { url, timeoutMs },\n { url, cause: error, ...(read ? { write: false } : {}) },\n );\n }\n if (read && isGalaError(error, 'TRANSPORT_ERROR') && error.write) {\n throw new GalaSDKError(\n 'TRANSPORT_ERROR',\n { url: error.url ?? url },\n { url: error.url ?? url, cause: error.cause, write: false },\n );\n }\n // Anything else is the requestor's own rejection (an app's axios interceptor error, say):\n // rethrown as it is, because the app's error handling produced it.\n throw error;\n } finally {\n disarm();\n externalSignal?.removeEventListener('abort', abortFromCaller);\n }\n}\n\nexport async function readResponseBody(response: HTTPResponse): Promise<unknown> {\n const text = await response.text();\n return parseJson(text) ?? text;\n}\n\n/** Read a case-insensitive response header from either supported header shape. */\nexport function readHeader(response: HTTPResponse, name: string): string | undefined {\n const headers = response.headers;\n if (headers === undefined) return undefined;\n if (hasHeaderGetter(headers)) {\n const value = headers.get(name);\n return value === null || value === '' ? undefined : value;\n }\n const value = Object.entries(headers).find(\n ([key]) => key.toLowerCase() === name.toLowerCase(),\n )?.[1];\n return value === undefined || value === '' ? undefined : value;\n}\n\n/** Read a Retry-After header (delta-seconds or an HTTP date) as non-negative milliseconds. */\nexport function readRetryAfter(response: HTTPResponse): number | undefined {\n const raw = readHeader(response, 'retry-after');\n if (raw === undefined) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const timestamp = Date.parse(raw);\n return Number.isNaN(timestamp) ? undefined : Math.max(0, timestamp - Date.now());\n}\n\n/** Read a non-negative integer block number header. */\nexport function readBlockNumberHeader(\n response: HTTPResponse,\n headerName = 'x-block-number',\n): number | undefined {\n const raw = readHeader(response, headerName);\n if (raw === undefined) return undefined;\n const blockNumber = Number(raw);\n return Number.isInteger(blockNumber) && blockNumber >= 0 ? blockNumber : undefined;\n}\n\nfunction hasHeaderGetter(\n headers: NonNullable<HTTPResponse['headers']>,\n): headers is { get(name: string): string | null } {\n return 'get' in headers && typeof headers.get === 'function';\n}\n","import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport type { HttpRequestor, HTTPResponse } from '../types/http_requestor.js';\n\n/** What the adapter reads of an axios response. */\nexport interface AxiosLikeResponse {\n status: number;\n data?: unknown;\n /** axios' `AxiosHeaders` (has `get`) or a plain header record. */\n headers?: unknown;\n}\n\n/** The request config the adapter hands to axios. */\nexport interface AxiosLikeConfig {\n headers: Record<string, string>;\n signal?: AbortSignal;\n validateStatus?: () => boolean;\n}\n\n/**\n * The part of an axios instance the adapter calls. Declared structurally, so the SDK takes no\n * dependency on axios and any axios instance (with its interceptors) satisfies it.\n */\nexport interface AxiosLikeInstance {\n get(url: string, config?: AxiosLikeConfig): Promise<unknown>;\n post(url: string, data?: unknown, config?: AxiosLikeConfig): Promise<unknown>;\n}\n\n/** Options of {@link httpRequestorFromAxios}. */\nexport interface AxiosRequestorOptions {\n /**\n * `true`: leave axios' default status validation alone, so a 4xx/5xx REJECTS through the\n * instance's own interceptors and the SDK rethrows what the app's error handling produced.\n * `false`: every HTTP status resolves, so the SDK classifies it itself (shadow submits,\n * apply-results reads); transport failures still reject.\n */\n rejectOnHttpError: boolean;\n /**\n * Request headers NOT to hand to axios, matched case-insensitively. Default `['content-type']`:\n * axios derives `Content-Type: application/json` from the object body it is given, and an\n * interceptor may set its own, so the SDK's copy would only be a second opinion.\n */\n omitHeaders?: readonly string[] | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * An axios interceptor may resolve something that is not a response at all (for example a string\n * for ECONNREFUSED). That is a transport failure, not an HTTP answer.\n */\nfunction isAxiosLikeResponse(value: unknown): value is AxiosLikeResponse {\n return isRecord(value) && typeof value['status'] === 'number';\n}\n\nfunction readAxiosHeader(headers: unknown, name: string): string | null {\n if (!isRecord(headers)) return null;\n const getter = headers['get'];\n if (typeof getter === 'function') {\n const value: unknown = getter.call(headers, name);\n return typeof value === 'string' ? value : null;\n }\n const match = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase());\n return typeof match?.[1] === 'string' ? match[1] : null;\n}\n\nfunction toHttpResponse(answer: unknown, url: string): HTTPResponse {\n if (!isAxiosLikeResponse(answer)) {\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url });\n }\n const { status, data, headers } = answer;\n return {\n ok: status >= 200 && status < 300,\n status,\n json: () => Promise.resolve(data),\n text: () => Promise.resolve(typeof data === 'string' ? data : JSON.stringify(data)),\n headers: { get: (name: string) => readAxiosHeader(headers, name) },\n };\n}\n\nfunction headersFor(\n init: RequestInit | undefined,\n omit: readonly string[],\n): Record<string, string> {\n const omitted = new Set(omit.map((name) => name.toLowerCase()));\n const raw = init?.headers;\n const entries: Array<[string, string]> =\n raw === undefined\n ? []\n : raw instanceof Headers\n ? [...raw.entries()]\n : Array.isArray(raw)\n ? raw.map(([name, value]): [string, string] => [String(name), String(value)])\n : Object.entries(raw).map(([name, value]): [string, string] => [name, String(value)]);\n return Object.fromEntries(entries.filter(([name]) => !omitted.has(name.toLowerCase())));\n}\n\n/**\n * An SDK {@link HttpRequestor} over an axios instance, so the SDK's requests travel through the\n * app's own base URL, interceptors and error handling.\n *\n * A POST's string body is parsed back to the object the SDK serialized it from (axios serializes\n * again, and an interceptor may read the object); a GET goes through `instance.get`. The answer\n * is an HTTP response whose `json()`/`text()` read `response.data`. An answer that is not an\n * axios response is a `TRANSPORT_ERROR` rejection, and so is a rejection that means no HTTP\n * answer arrived (the original error is `cause`): any rejection with `rejectOnHttpError: false`\n * (every status resolves there), an axios error without a `response` with `true`. Any other\n * rejection (an interceptor's error for a 4xx, say) is rethrown unchanged, and so is an abort.\n *\n * Pair it with `ChainGateway`'s `dexBackendBaseUrl: ''` when the instance owns the base URL.\n *\n * @example\n * ```ts\n * const submitGateway = new ChainGateway({\n * dexBackendBaseUrl: '',\n * httpRequestor: httpRequestorFromAxios(chainGatewayInstance, { rejectOnHttpError: true }),\n * });\n * ```\n */\nexport function httpRequestorFromAxios(\n instance: AxiosLikeInstance,\n options: AxiosRequestorOptions,\n): HttpRequestor {\n const omit = options.omitHeaders ?? ['content-type'];\n return async (uri, init) => {\n const signal = init?.signal ?? undefined;\n const config: AxiosLikeConfig = {\n headers: headersFor(init, omit),\n ...(signal ? { signal } : {}),\n ...(options.rejectOnHttpError ? {} : { validateStatus: () => true }),\n };\n const isPost = (init?.method ?? 'GET').toUpperCase() === 'POST';\n const body: unknown =\n isPost && typeof init?.body === 'string' ? JSON.parse(init.body) : undefined;\n let answer: unknown;\n try {\n answer = await (isPost ? instance.post(uri, body, config) : instance.get(uri, config));\n } catch (error: unknown) {\n // An abort is the caller's or the SDK's timeout, and the request layer knows which.\n if (signal?.aborted === true || !isTransportRejection(error, options.rejectOnHttpError)) {\n throw error;\n }\n throw new GalaSDKError('TRANSPORT_ERROR', { url: uri }, { url: uri, cause: error });\n }\n return toHttpResponse(answer, uri);\n };\n}\n\n/**\n * Whether an axios rejection means no HTTP answer arrived. With `rejectOnHttpError: false` every\n * status resolves, so any rejection is one. With `true`, a 4xx/5xx rejects too, so only an axios\n * error that carries no `response` is (an interceptor's own error is an app answer and passes\n * through; an app whose interceptors turn network errors into their own class names it in\n * `ChainGatewayOptions.isTransportFailure`).\n */\nfunction isTransportRejection(error: unknown, rejectOnHttpError: boolean): boolean {\n if (!rejectOnHttpError) return true;\n return isRecord(error) && error['isAxiosError'] === true && error['response'] === undefined;\n}\n","import type { BrowserWalletProvider } from '../classes/signers.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { stripEip712DomainType } from './chain_dto_signing.js';\n\n/**\n * The part of an ethers v6 signer (`JsonRpcSigner`, `Wallet`) the adapter calls. Declared\n * structurally, so the SDK takes no dependency on ethers and an ethers object satisfies it as is.\n */\nexport interface EthersLikeSigner {\n signTypedData(\n domain: Record<string, unknown>,\n types: Record<string, Array<{ name: string; type: string }>>,\n value: Record<string, unknown>,\n ): Promise<string>;\n signMessage(message: string): Promise<string>;\n}\n\n/** The part of an ethers v6 provider (`BrowserProvider`) the adapter calls. */\nexport interface EthersLikeProvider {\n getSigner(): Promise<EthersLikeSigner>;\n /** The raw JSON-RPC passthrough (`BrowserProvider.send`). */\n send(method: string, params: unknown[]): Promise<unknown>;\n}\n\n/** Options of {@link eip1193ProviderFromEthers}. */\nexport interface EthersEip1193Options {\n /**\n * Signs a `personal_sign` message when the provider cannot or should not: a wallet SDK that\n * signs through its own object (TrustWallet's `web3Wallet.signMessage`). When set it answers\n * every `personal_sign`, and the provider is not touched for it.\n */\n personalSign?: ((message: string) => Promise<string>) | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isTypedDataTypes(\n value: unknown,\n): value is Record<string, Array<{ name: string; type: string }>> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (fields) =>\n Array.isArray(fields) &&\n fields.every(\n (field) =>\n isRecord(field) &&\n typeof field['name'] === 'string' &&\n typeof field['type'] === 'string',\n ),\n )\n );\n}\n\nfunction malformed(method: string): GalaSDKError {\n return new GalaSDKError('MALFORMED_WALLET_REQUEST', { method });\n}\n\n/** Splits `eth_signTypedData_v4` params (`[account, JSON payload]`) into what ethers' signer takes. */\nfunction readTypedDataRequest(params: unknown[] | undefined): {\n domain: Record<string, unknown>;\n types: Record<string, Array<{ name: string; type: string }>>;\n message: Record<string, unknown>;\n} {\n const raw = params?.[1];\n let payload: unknown;\n try {\n payload = typeof raw === 'string' ? JSON.parse(raw) : raw;\n } catch {\n throw malformed('eth_signTypedData_v4');\n }\n if (!isRecord(payload)) throw malformed('eth_signTypedData_v4');\n const { domain, types, message } = payload;\n if (!isRecord(domain) || !isTypedDataTypes(types) || !isRecord(message)) {\n throw malformed('eth_signTypedData_v4');\n }\n // ethers refuses an explicit EIP712Domain type; the JSON-RPC form includes it.\n return { domain, types: stripEip712DomainType(types), message };\n}\n\n/**\n * An EIP-1193 provider over an ethers v6 provider, for {@link BrowserWalletSigner}: apps whose\n * wallet connection is an ethers `BrowserProvider` sign through the very ethers calls they always\n * made, with no hand-written shim.\n *\n * - `eth_chainId` is `provider.send('eth_chainId', [])`: the wallet's LIVE chain. Never\n * `provider.getNetwork()`, which ethers caches and does not invalidate on `chainChanged`, so a\n * user who switches networks after connecting would sign against a stale chainId.\n * - `eth_signTypedData_v4` parses the `[account, JSON]` params and calls\n * `signer.signTypedData(domain, types, message)` with `EIP712Domain` removed from `types`.\n * - `personal_sign` is `options.personalSign(message)` when given, else `signer.signMessage`.\n * - Anything else is `UNSUPPORTED_WALLET_METHOD`; a malformed request is\n * `MALFORMED_WALLET_REQUEST`; a missing provider is `WALLET_UNAVAILABLE`.\n *\n * `provider` may be `null`/`undefined` (nothing connected): a request that needs it then fails\n * with `WALLET_UNAVAILABLE` rather than at construction, so a signer can be built before the\n * connection state is known.\n *\n * @example\n * ```ts\n * const signer = new BrowserWalletSigner(eip1193ProviderFromEthers(browserProvider), account, {\n * scheme: 'eip712',\n * });\n * ```\n */\nexport function eip1193ProviderFromEthers(\n provider: EthersLikeProvider | null | undefined,\n options: EthersEip1193Options = {},\n): BrowserWalletProvider {\n const connected = (): EthersLikeProvider => {\n if (provider === null || provider === undefined) {\n throw new GalaSDKError('WALLET_UNAVAILABLE', {});\n }\n return provider;\n };\n return {\n request: async ({ method, params }) => {\n switch (method) {\n case 'eth_chainId':\n return connected().send('eth_chainId', []);\n case 'eth_signTypedData_v4': {\n const wallet = connected();\n const { domain, types, message } = readTypedDataRequest(params);\n return (await wallet.getSigner()).signTypedData(domain, types, message);\n }\n case 'personal_sign': {\n const message = params?.[0];\n if (typeof message !== 'string') throw malformed('personal_sign');\n if (options.personalSign !== undefined) return options.personalSign(message);\n return (await connected().getSigner()).signMessage(message);\n }\n default:\n throw new GalaSDKError('UNSUPPORTED_WALLET_METHOD', { method });\n }\n },\n };\n}\n","/**\n * True when a rejection of a `fetch`-based requestor means NO HTTP ANSWER ARRIVED: the network\n * failed, the connection was reset, the host did not resolve, CORS blocked it. For a write that\n * is not a refusal (the request may have been queued), so this is the default\n * `ChainGatewayOptions.isTransportFailure` for a requestor that wraps `fetch` and rejects with\n * its own errors.\n *\n * - Yes: a `TypeError` (what `fetch` rejects with in every engine: `Failed to fetch`, `Load failed`,\n * `NetworkError when attempting to fetch resource`, undici's `fetch failed`), recognised by name\n * too so one from another realm (an extension page, an iframe) still counts, and a\n * `DOMException` named `NetworkError`.\n * - No: an abort (`AbortError`) or a timeout (`TimeoutError`). The SDK's own request layer knows\n * whether its timer or the caller's signal aborted, and reports those itself\n * (`REQUEST_TIMEOUT`, or the caller's own abort unchanged); claiming them here would turn the\n * caller's cancel into \"maybe queued\".\n * - No: anything else, including an SDK error and a value that is not an object.\n *\n * It never throws.\n *\n * @example\n * ```ts\n * new ChainGateway({ dexBackendBaseUrl, httpRequestor: galaFetch, isTransportFailure: isFetchTransportFailure });\n * ```\n */\nexport function isFetchTransportFailure(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n try {\n const name: unknown = 'name' in error ? error.name : undefined;\n if (name === 'AbortError' || name === 'TimeoutError') return false;\n return error instanceof TypeError || name === 'TypeError' || name === 'NetworkError';\n } catch {\n // A hostile or revoked object (a Proxy that throws on property access) proves nothing.\n return false;\n }\n}\n","/**\n * What a failure means for the operation that raised it, as one vocabulary for every app.\n *\n * - `rejected`: the CHAIN refused the request (a definite no). Nothing was applied, so a NEW\n * request is safe.\n * - `unknown`: the request MAY have been applied (a timeout, a broken connection, an\n * acknowledgement that proves nothing, a failed confirmation). Never submit again under a fresh\n * key: keep `error.uniqueKey` and confirm it.\n * - `not_queued`: the gateway refused the write before queueing it. Nothing is pending.\n * - `not_sent`: the request never left (`error.phase === 'pre_send'`) for a reason outside the\n * call itself: the signer or the wallet failed (locked, unreachable, the person declined), the\n * key provider or the token resolver failed, or no key was available yet. Nothing is pending and\n * nothing was transmitted, so repeating the call is safe and may succeed once the cause (an\n * unlocked wallet) is gone.\n * - `invalid_input`: the call itself cannot work (a bad argument, a missing signer or wallet, an\n * unknown token or pool, a corrupt stored key). Repeating the same call fails the same way.\n * Such an error is also pre-send (`isPreSendError`), but the input is what has to change.\n * - `transient`: a read or connection failed with no state change. Repeating the same call is safe\n * and may succeed.\n *\n * This module has no imports: the failure view (`FailureView.outcome`) and the classifier both\n * read the closed set from here.\n */\nexport const FAILURE_OUTCOMES = [\n 'rejected',\n 'unknown',\n 'not_queued',\n 'not_sent',\n 'invalid_input',\n 'transient',\n] as const;\n\n/** One member of {@link FAILURE_OUTCOMES}. */\nexport type FailureOutcome = (typeof FAILURE_OUTCOMES)[number];\n","import { GALA_ERROR_PHASES, type GalaErrorPhase } from '../classes/error_phases.js';\nimport { FAILURE_OUTCOMES, type FailureOutcome } from './failure_outcomes.js';\n\n/**\n * A failure as a PLAIN OBJECT: the facts the SDKs' guards and classifiers (gswap-sdk's\n * `classifyFailure`) read, and nothing else. A real `GalaSDKError` is one (every field below is on\n * it, and on every product subclass); so is the wrapper an app makes from an SDK error to carry\n * through its own layers (an app's own failure class or error data), which\n * has a `code` and `params` but is not an `instanceof` anything the SDK owns. gswap-sdk's\n * `classifyFailure`, `isRelayableRefusal`, `isUnprovenAcknowledgement`, `isUninterpretedAnswer`,\n * `isPreSendError`, `isShadowError`, `isNoMarket` and `mayHaveBeenQueued` all accept such an\n * object wherever they accept an SDK error, and decide from the SAME fields in the same way, so an\n * app never has to keep the original error just to ask.\n *\n * Only `code` is required. A field that is missing, or has the wrong type, reads as absent: a view\n * with no `status` is not a 404. Nothing here is text: the SDK never reads `message` of a view.\n *\n * READ OR WRITE: a view is a WRITE's unless it says it is a read. This fails CLOSED on purpose:\n * a 5xx on a write may have been queued (`unknown`, no retry) and the same 5xx on a read changed\n * nothing (`transient`, retry), so a wrapper that drops its `uniqueKey` must never turn the first\n * into the second. A view is a read ONLY when it states `write: false` and has no `uniqueKey`;\n * `GalaSDKError.write` is already set that way for every SDK read. {@link isWriteView}\n * is the one definition.\n *\n * APP ERRORS: a code the SDK catalog does not define is `unknown` (the SDK cannot say what\n * happened, and a wrong \"failed\" invites a duplicate), unless the view declares `outcome`.\n */\nexport interface FailureView {\n /** The catalog code (`'HTTP_ERROR'`, `'CHAIN_REJECTED'`, ...). A string the SDK does not know classifies as `unknown`. */\n readonly code: string;\n /** The error's flat params (`status` of an `HTTP_ERROR`, `reason` of a `SIGNING_FAILED`, ...). */\n readonly params?: Readonly<Record<string, unknown>> | undefined;\n /** The HTTP status of the answer the failure was made from. */\n readonly status?: number | undefined;\n /** How far the request got; when absent, the catalog's phase for `code`. */\n readonly phase?: GalaErrorPhase | undefined;\n /** The `uniqueKey` of the WRITE this is about; its presence makes the failure a write's. */\n readonly uniqueKey?: string | undefined;\n /**\n * `false` says the failed call was a READ (no `uniqueKey` to confirm, nothing pending). Anything\n * else, including absent, is a write: see the note on {@link FailureView}. With a `uniqueKey`\n * the failure is a write whatever this says.\n */\n readonly write?: boolean | undefined;\n /**\n * What an error the APP raised means, for a `code` the SDK catalog does not define (`'POSITION_STALE'`,\n * `'AMOUNT_SIDE'`): `not_sent` for a step that failed before anything was signed or sent, and so\n * on. The SDK honours it ONLY for such a code: for a catalog code the SDK's own table decides, so\n * an app cannot declare a refusal the SDK knows to be unknown as safe. A non-catalog code with no\n * `outcome` stays `unknown`, and `mayHaveBeenQueued` is then `true`.\n */\n readonly outcome?: FailureOutcome | undefined;\n /**\n * WITHHOLD-ONLY: `false` takes Retry away from the declared `outcome` (an app's `DID_NOT_QUEUE`\n * is `{ outcome: 'not_queued', retryable: false }`, the SDK's `NOT_QUEUED_FINAL`). Any other\n * value, `true` included, reads as absent: a view can never GRANT Retry to an outcome that does\n * not have it, and it is read only together with `outcome`, for a code the catalog does not\n * define.\n */\n readonly retryable?: false | undefined;\n /** True when the failure came from the shadow (dark) path. */\n readonly shadow?: boolean | undefined;\n /** True for \"that thing does not exist\" (`GalaSDKError.notFound`: a market, for gswap-sdk). */\n readonly notFound?: boolean | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Reads the failure view of any value: a `GalaSDKError`, or a plain object with a string `code`\n * (and, optionally, `params`, `status`, `phase`, `uniqueKey`, `shadow`, `notFound`). Anything else\n * (a string, a wallet error with a numeric `code`, `null`) has no view and is `undefined`.\n *\n * Having a view does not mean the SDK knows the code: an ethers error is `{ code:\n * 'ACTION_REJECTED' }` and has a view too. The SDK's guards compare the code with the catalog.\n *\n * @example\n * ```ts\n * const view = toFailureView(error); // an SDK error, or an app's `{ code, params, status }` wrapper\n * if (view?.code === 'CHAIN_REJECTED') showChainRejection(view.params);\n * ```\n */\nexport function toFailureView(value: unknown): FailureView | undefined {\n if (!isRecord(value)) return undefined;\n const { code, params, status, phase, uniqueKey, write, outcome, retryable, shadow, notFound } =\n value;\n if (typeof code !== 'string' || code === '') return undefined;\n return {\n code,\n params: isRecord(params) && !Array.isArray(params) ? params : undefined,\n status: typeof status === 'number' && Number.isFinite(status) ? status : undefined,\n phase: GALA_ERROR_PHASES.find((known) => known === phase),\n uniqueKey: typeof uniqueKey === 'string' && uniqueKey !== '' ? uniqueKey : undefined,\n write: typeof write === 'boolean' ? write : undefined,\n outcome: FAILURE_OUTCOMES.find((known) => known === outcome),\n retryable: retryable === false ? false : undefined,\n shadow: typeof shadow === 'boolean' ? shadow : undefined,\n notFound: typeof notFound === 'boolean' ? notFound : undefined,\n };\n}\n\n/**\n * True when a failure is a WRITE's: it names a `uniqueKey`, or it does not say `write: false`.\n * Fail-closed (see {@link FailureView}): only an explicit read is a read.\n */\nexport function isWriteView(view: FailureView): boolean {\n return view.uniqueKey !== undefined || view.write !== false;\n}\n\n/** A param of a view, when it is a string. */\nexport function stringParamOf(view: FailureView, name: string): string | undefined {\n const value = view.params?.[name];\n return typeof value === 'string' ? value : undefined;\n}\n\n/** A param of a view, when it is a finite number. */\nexport function numberParamOf(view: FailureView, name: string): number | undefined {\n const value = view.params?.[name];\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n","import type { GalaChainTokenClassKey } from '../types/token.js';\n\n/**\n * Token class keys that never throw: the `$`-joined composite key and the non-throwing parsers.\n * This module imports nothing at run time (the key type is erased), so an app shell that reads a\n * stored key pays for a few hundred bytes, never for the error class or the catalog. The parser\n * that THROWS an SDK error on a bad key (gswap-sdk's `parseTokenClassKey`) splits with\n * {@link splitClassKey} too, so the two can never disagree about a key.\n */\n\n/** Return the `$`-joined composite key used by GalaChain object identities. */\nexport function compositeKeyOf(token: GalaChainTokenClassKey): string {\n return [token.collection, token.category, token.type, token.additionalKey].join('$');\n}\n\n/**\n * Splits `collection<d>category<d>type<d>additionalKey` from the right, or `undefined` when there\n * are fewer than four segments or any of the four is empty. The one place the split is written;\n * the strict `parseTokenClassKey` calls it too.\n *\n * The LAST three segments are always `category`, `type` and `additionalKey`; everything before\n * them is the `collection`. Parsing from the right is required because real collections contain\n * the `$` delimiter themselves (for example `$GMUSIC`), so a plain left-to-right `split('$')`\n * shifts every field.\n */\nexport function splitClassKey(\n key: string,\n delimiter: '|' | '$',\n): GalaChainTokenClassKey | undefined {\n const segments = key.split(delimiter);\n const tail = segments.slice(-3);\n const collection = segments.slice(0, -3).join(delimiter);\n if (segments.length < 4 || collection.length === 0 || tail.some((part) => part.length === 0)) {\n return undefined;\n }\n const [category, type, additionalKey] = tail;\n return {\n collection,\n category: category as string,\n type: type as string,\n additionalKey: additionalKey as string,\n };\n}\n\n/**\n * The non-throwing `parseTokenClassKey`: the class key, or `undefined` when `value` is not\n * one. A string is split exactly as `parseTokenClassKey` splits it (`|` form when it contains a\n * `|`, else `$`, from the right, all four parts non-empty). Unlike `parseTokenClassKey`, an\n * object is VALIDATED, not just copied: all four fields must be non-empty strings. Anything else\n * (`undefined`, `null`, a number, an array) is `undefined`, so it is safe on untrusted input (a\n * stored token, a URL parameter, a wallet row) without a `try`/`catch`.\n *\n * Use {@link tryParseCompositeKey} instead when only the `$` form is valid input.\n *\n * @example\n * ```ts\n * const key = tryParseTokenClassKey(row.compositeKey);\n * if (key === undefined) return failClosed(); // no class is known: never invent one from a symbol\n * ```\n */\nexport function tryParseTokenClassKey(value: unknown): GalaChainTokenClassKey | undefined {\n if (typeof value === 'string') return splitClassKey(value, value.includes('|') ? '|' : '$');\n if (typeof value !== 'object' || value === null) return undefined;\n try {\n const { collection, category, type, additionalKey } = value as Record<string, unknown>;\n if (\n typeof collection !== 'string' ||\n typeof category !== 'string' ||\n typeof type !== 'string' ||\n typeof additionalKey !== 'string' ||\n collection === '' ||\n category === '' ||\n type === '' ||\n additionalKey === ''\n ) {\n return undefined;\n }\n return { collection, category, type, additionalKey };\n } catch {\n // A getter or proxy that throws is not a token class key.\n return undefined;\n }\n}\n\n/**\n * True for a token class key OBJECT: `collection`, `category`, `type` and `additionalKey` are all\n * non-empty strings (other fields, an `instance` say, are allowed). A string is never one: parse it\n * with {@link tryParseTokenClassKey}. Never throws (a getter that throws is \"not a key\").\n *\n * @example\n * ```ts\n * if (isTokenClassKey(value)) console.log(compositeKeyOf(value));\n * ```\n */\nexport function isTokenClassKey(value: unknown): value is GalaChainTokenClassKey {\n return typeof value === 'object' && value !== null && tryParseTokenClassKey(value) !== undefined;\n}\n\n/**\n * Parses a `$`-joined composite key (`Collection$Category$Type$AdditionalKey`, what\n * {@link compositeKeyOf} writes) and nothing else, or `undefined`. It is {@link tryParseTokenClassKey}\n * for a string that may ONLY be in the `$` form: a key that contains `|` is NOT read as the pipe\n * form here (it stays part of a segment), and only a string is accepted. The split is from the\n * right, so a collection that itself contains `$` (production's `$GMUSIC`, stage's\n * `$GMUSIC_TEST1`) stays whole; `'GALA'`, `'GALA$Unit$none'`, `'ETIME$$$'`, `'GALA$Unit$none$'` and\n * `'$$$$'` are `undefined`.\n *\n * It replaces an app's own `parseCompositeKey(key): Components | null` (`?? null`), which had\n * exactly these semantics.\n *\n * @example\n * ```ts\n * tryParseCompositeKey('$GMUSIC_TEST1$Unit$none$none')?.collection; // '$GMUSIC_TEST1'\n * tryParseCompositeKey('GALA$Unit$none'); // undefined\n * ```\n */\nexport function tryParseCompositeKey(value: unknown): GalaChainTokenClassKey | undefined {\n return typeof value === 'string' ? splitClassKey(value, '$') : undefined;\n}\n","/**\n * The shape of a write `uniqueKey`, with NO imports: the pending-swap store and the failure guards\n * need only this check, and importing it from `unique_key.ts` would drag in `GalaSDKError` and the\n * whole error catalog for it.\n */\n\n/** The swap backend's apply-results key constraint (`apply-results.dto.ts`). */\nconst UNIQUE_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;\n\n/**\n * True when `uniqueKey` is a usable write key: 1 to 128 characters of `A-Za-z0-9._:-`, the shape\n * the apply-results route accepts. The one definition behind `assertUniqueKey`, `confirm()` and\n * the pending-swap store, so they can never disagree about what a valid key is.\n */\nexport function isValidUniqueKey(uniqueKey: unknown): uniqueKey is string {\n return typeof uniqueKey === 'string' && UNIQUE_KEY_PATTERN.test(uniqueKey);\n}\n","import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { isValidUniqueKey } from './unique_key_syntax.js';\n\n/**\n * The `uniqueKey` prefix the Gala Wallet and the gSwap web app have always sent\n * (`galaswap-operation-<uuid>`). The backend does not depend on it: the chain-write verifier\n * only requires a non-empty key of at most 256 characters, and apply-results accepts\n * `[A-Za-z0-9._:-]{1,128}`; the only code that mints a prefixed key itself is the server-side v1\n * trade builder, which nothing reads back by prefix.\n */\nexport const DEFAULT_UNIQUE_KEY_PREFIX = 'galaswap-operation-';\n\n/** Options shared by the services that mint `uniqueKey`s for writes. */\nexport interface UniqueKeyOptions {\n /**\n * Prefix of every minted `uniqueKey` (`<prefix><uuid>`). Defaults to\n * `DEFAULT_UNIQUE_KEY_PREFIX` (`galaswap-operation-`).\n */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/** A canonical UUID is 36 characters; the apply-results key limit is 128. */\nconst MAX_UNIQUE_KEY_PREFIX_LENGTH = 128 - 36;\nconst UNIQUE_KEY_PREFIX_PATTERN = /^[A-Za-z0-9._:-]*$/u;\n\n/**\n * Validates a caller-supplied `uniqueKey` prefix. The whole key (`<prefix><uuid>`) must stay a\n * valid apply-results key, otherwise `confirm()` could never read the outcome of the write.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY_PREFIX` when the prefix has characters outside\n * `A-Za-z0-9._:-` or is longer than 92 characters.\n */\nexport function resolveUniqueKeyPrefix(prefix: string | undefined): string {\n if (prefix === undefined) return DEFAULT_UNIQUE_KEY_PREFIX;\n if (!UNIQUE_KEY_PREFIX_PATTERN.test(prefix) || prefix.length > MAX_UNIQUE_KEY_PREFIX_LENGTH) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY_PREFIX', {\n uniqueKeyPrefix: prefix,\n maxLength: MAX_UNIQUE_KEY_PREFIX_LENGTH,\n });\n }\n return prefix;\n}\n\n/**\n * Validates a caller-supplied write `uniqueKey`: 1 to 128 characters of `A-Za-z0-9._:-`, the\n * shape the apply-results route accepts, so the write's outcome can always be read back with\n * `confirm()`. A key is one attempt's identity: reuse it only to retry that same attempt.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY` otherwise.\n */\nexport function assertUniqueKey(uniqueKey: string): void {\n if (!isValidUniqueKey(uniqueKey)) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY', { uniqueKey: String(uniqueKey) });\n }\n}\n\n/** The part of `globalThis.crypto` a uniqueKey needs: the one CSPRNG every target can offer. */\ninterface RandomValuesSource {\n getRandomValues?: ((array: Uint8Array) => unknown) | undefined;\n}\n\n/**\n * A random version-4 UUID (RFC 9562) in the canonical lowercase `8-4-4-4-12` form, byte for byte\n * the shape `crypto.randomUUID()` returns, built from `crypto.getRandomValues`. `randomUUID` is\n * NOT used: React Native's Hermes has no `crypto.randomUUID`, so a write would fail with\n * \"undefined is not a function\", while `getRandomValues` is what browsers, Node (>= 19 as a\n * global), MV3 service workers and Hermes with `react-native-get-random-values` all provide.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when there is no `getRandomValues`: a key minted from\n * `Math.random` could collide with another attempt's, so the SDK refuses rather than degrade.\n */\nfunction randomUuidV4(): string {\n const source = (globalThis as { crypto?: RandomValuesSource | undefined }).crypto;\n if (typeof source?.getRandomValues !== 'function') {\n throw new GalaSDKError('CSPRNG_UNAVAILABLE', {});\n }\n // Filled in place: a polyfill is not relied on to return the array.\n const bytes = new Uint8Array(16);\n source.getRandomValues(bytes);\n const hex: string[] = [];\n bytes.forEach((byte, index) => {\n // Version nibble 4 in byte 6, variant bits 10 in byte 8; everything else stays random.\n const value = index === 6 ? (byte & 0x0f) | 0x40 : index === 8 ? (byte & 0x3f) | 0x80 : byte;\n hex.push(value.toString(16).padStart(2, '0'));\n });\n const text = hex.join('');\n return [\n text.slice(0, 8),\n text.slice(8, 12),\n text.slice(12, 16),\n text.slice(16, 20),\n text.slice(20),\n ].join('-');\n}\n\n/**\n * A fresh per-attempt key: `<prefix><random UUID>`, the UUID a random version-4 one.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when the platform has no `crypto.getRandomValues`\n * (install a polyfill such as `react-native-get-random-values` on React Native).\n */\nexport function createUniqueKey(prefix: string): string {\n return `${prefix}${randomUuidV4()}`;\n}\n","/**\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","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","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","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","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","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","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","import BigNumber from 'bignumber.js';\nimport type {\n GalaChainNftCollectionAuthorization,\n GalaChainPage,\n GalaChainPublicKey,\n GalaChainTokenBalance,\n GalaChainTokenClass,\n GalaChainTokenHold,\n} from './types.js';\n\n/**\n * Readers of the chain's answers. Each returns the typed value, or `undefined` when the value is\n * not what GalaChain answers (the caller turns that into `GATEWAY_READ_RESPONSE_INVALID`), so an\n * answer is never half-trusted: a balance with a numeric quantity, a hold without its expiry or a\n * token class without its symbol is refused whole, never passed on with a hole in it.\n */\n\ntype Row = Readonly<Record<string, unknown>>;\n\nfunction isRow(value: unknown): value is Row {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value !== '';\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\n/** A non-negative amount as the chain writes it: a decimal string `bignumber.js` reads exactly. */\nfunction isAmount(value: unknown): value is string {\n if (typeof value !== 'string' || value.trim() !== value || value === '') return false;\n const amount = new BigNumber(value);\n return amount.isFinite() && !amount.isNegative();\n}\n\nfunction stringList(value: unknown): string[] | undefined {\n return Array.isArray(value) && value.every(isString) ? [...value] : undefined;\n}\n\n/** A list of `parse`d entries, `undefined` when it is not a list or any entry is unusable. */\nfunction listOf<T>(value: unknown, parse: (entry: unknown) => T | undefined): T[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const parsed: T[] = [];\n for (const entry of value) {\n const item = parse(entry);\n if (item === undefined) return undefined;\n parsed.push(item);\n }\n return parsed;\n}\n\n/** An optional field: absent or `undefined` is fine, present must pass `check`. */\nfunction optional<T>(\n row: Row,\n key: string,\n check: (value: unknown) => value is T,\n): T | undefined | null {\n const value = row[key];\n if (value === undefined) return undefined;\n return check(value) ? value : null;\n}\n\nexport function parseHold(value: unknown): GalaChainTokenHold | undefined {\n if (!isRow(value)) return undefined;\n const { created, createdBy, expires, instanceId, lockAuthority, quantity } = value;\n const name = optional(value, 'name', isString);\n const vestingPeriodStart = optional(value, 'vestingPeriodStart', isFiniteNumber);\n if (\n !isFiniteNumber(created) ||\n !isString(createdBy) ||\n !isFiniteNumber(expires) ||\n !isString(instanceId) ||\n !isString(lockAuthority) ||\n !isAmount(quantity) ||\n name === null ||\n vestingPeriodStart === null\n ) {\n return undefined;\n }\n return {\n created,\n createdBy,\n expires,\n instanceId,\n lockAuthority,\n ...(name === undefined ? {} : { name }),\n quantity,\n ...(vestingPeriodStart === undefined ? {} : { vestingPeriodStart }),\n };\n}\n\n/** A hold list that the chain may leave out (older balances have no `inUseHolds`). */\nfunction holdsOf(value: unknown): GalaChainTokenHold[] | undefined {\n return value === undefined ? [] : listOf(value, parseHold);\n}\n\nexport function parseBalance(value: unknown): GalaChainTokenBalance | undefined {\n if (!isRow(value)) return undefined;\n const { owner, collection, category, type, additionalKey, quantity } = value;\n const instanceIds = value['instanceIds'] === undefined ? [] : stringList(value['instanceIds']);\n const lockedHolds = holdsOf(value['lockedHolds']);\n const inUseHolds = holdsOf(value['inUseHolds']);\n if (\n !isNonEmptyString(owner) ||\n !isNonEmptyString(collection) ||\n !isNonEmptyString(category) ||\n !isNonEmptyString(type) ||\n !isNonEmptyString(additionalKey) ||\n !isAmount(quantity) ||\n instanceIds === undefined ||\n lockedHolds === undefined ||\n inUseHolds === undefined\n ) {\n return undefined;\n }\n return {\n owner,\n collection,\n category,\n type,\n additionalKey,\n quantity,\n instanceIds,\n lockedHolds,\n inUseHolds,\n };\n}\n\nexport function parseBalances(value: unknown): GalaChainTokenBalance[] | undefined {\n return listOf(value, parseBalance);\n}\n\n/** The required string fields of a token class, in the order the chain serializes them. */\nconst CLASS_STRINGS = [\n 'collection',\n 'category',\n 'type',\n 'additionalKey',\n 'network',\n 'maxSupply',\n 'maxCapacity',\n 'name',\n 'symbol',\n 'description',\n 'image',\n 'totalBurned',\n 'totalMintAllowance',\n 'totalSupply',\n] as const;\n\n/** The optional string fields of a token class (`FetchTokenClassesWithSupply` adds the two supplies). */\nconst CLASS_OPTIONAL_STRINGS = [\n 'contractAddress',\n 'metadataAddress',\n 'rarity',\n 'quantityLimit',\n 'knownMintSupply',\n 'knownMintAllowanceSupply',\n] as const;\n\nconst CLASS_KEY_PARTS: ReadonlySet<string> = new Set([\n 'collection',\n 'category',\n 'type',\n 'additionalKey',\n]);\n\nexport function parseTokenClass(value: unknown): GalaChainTokenClass | undefined {\n if (!isRow(value)) return undefined;\n const strings: Record<string, string> = {};\n for (const key of CLASS_STRINGS) {\n const field = value[key];\n if (!isString(field) || (CLASS_KEY_PARTS.has(key) && field === '')) return undefined;\n strings[key] = field;\n }\n const extras: Record<string, string> = {};\n for (const key of CLASS_OPTIONAL_STRINGS) {\n const field = optional(value, key, isString);\n if (field === null) return undefined;\n if (field !== undefined) extras[key] = field;\n }\n const { decimals, isNonFungible } = value;\n const authorities = stringList(value['authorities']);\n if (\n typeof decimals !== 'number' ||\n !Number.isSafeInteger(decimals) ||\n decimals < 0 ||\n typeof isNonFungible !== 'boolean' ||\n authorities === undefined\n ) {\n return undefined;\n }\n return {\n ...strings,\n decimals,\n isNonFungible,\n authorities,\n ...extras,\n } as unknown as GalaChainTokenClass;\n}\n\nexport function parseTokenClasses(value: unknown): GalaChainTokenClass[] | undefined {\n return listOf(value, parseTokenClass);\n}\n\nexport function parseNftCollectionAuthorization(\n value: unknown,\n): GalaChainNftCollectionAuthorization | undefined {\n if (!isRow(value)) return undefined;\n const { collection } = value;\n const authorizedUsers = stringList(value['authorizedUsers']);\n if (!isNonEmptyString(collection) || authorizedUsers === undefined) return undefined;\n return { collection, authorizedUsers };\n}\n\n/** A registered public key (`GetPublicKey`): a non-empty `publicKey`, and `signing` when present. */\nexport function parsePublicKey(value: unknown): GalaChainPublicKey | undefined {\n if (!isRow(value)) return undefined;\n const { publicKey } = value;\n const signing = optional(value, 'signing', isNonEmptyString);\n if (!isNonEmptyString(publicKey) || signing === null) return undefined;\n return { publicKey, ...(signing === undefined ? {} : { signing }) };\n}\n\n/** A paginated answer (`{ results, nextPageBookmark }`); an empty bookmark means the last page. */\nexport function parsePage<T>(\n value: unknown,\n parse: (entry: unknown) => T | undefined,\n): GalaChainPage<T> | undefined {\n if (!isRow(value)) return undefined;\n const results = listOf(value['results'], parse);\n const bookmark = optional(value, 'nextPageBookmark', isString);\n if (results === undefined || bookmark === null) return undefined;\n return { results, nextPageBookmark: bookmark === '' ? undefined : bookmark };\n}\n","import { GalaSDKError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { buildRequestHeaders, readResponseBody, requestWithTimeout } from '../utils/transport.js';\nimport type { GatewayReadMethod } from './types.js';\n\n/** What every read is sent with. */\nexport interface ReadTransport {\n readonly gatewayBaseUrl: string;\n readonly requestor: HttpRequestor;\n readonly timeoutMs: number;\n readonly wire: WireOptions | undefined;\n}\n\n/** The gateway channel a token lives on. */\nexport type GatewayChannel = 'asset' | 'music';\n\n/** The chaincode contract each read method belongs to (part of its URL). */\nconst CONTRACT_OF: Readonly<Record<GatewayReadMethod, 'token-contract' | 'public-key-contract'>> = {\n FetchBalances: 'token-contract',\n FetchTokenClasses: 'token-contract',\n FetchTokenClassesWithSupply: 'token-contract',\n FetchTokenClassesWithPagination: 'token-contract',\n FetchNftCollectionAuthorizationsWithPagination: 'token-contract',\n GetPublicKey: 'public-key-contract',\n};\n\n/**\n * Methods whose successful answer carries no `Status`: the connect-api GalaChain proxies answer\n * `GetPublicKey` with `{ Data: { publicKey } }` only (recorded 2026-10-14, prod and stage,\n * `tests/fixtures/public-key-recorded.json`). A `Status` they do send is still checked.\n */\nconst ANSWERED_WITHOUT_STATUS: ReadonlySet<GatewayReadMethod> = new Set<GatewayReadMethod>([\n 'GetPublicKey',\n]);\n\n/**\n * The channel of a collection: `$MUSIC` (and `MUSIC`, any case) lives on the gateway's `music`\n * channel, every other collection (`$GMUSIC` included) on `asset`.\n */\nexport function channelOf(collection: string | undefined): GatewayChannel {\n return collection !== undefined && /^\\$?music$/iu.test(collection) ? 'music' : 'asset';\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\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 * The chain's error object of a refused answer: GalaChain's gateway nests it as\n * `{ error: { Status: 0, ErrorKey, Message, ErrorPayload }, message }`; an older answer carries\n * `Status` / `ErrorKey` / `Message` at the top.\n */\nexport function chainErrorOf(body: unknown): Record<string, unknown> | undefined {\n if (!isRecord(body)) return undefined;\n const nested = body['error'];\n return isRecord(nested) ? nested : body;\n}\n\n/**\n * POSTs one read and returns the chain's `Data`. Reads change nothing, so every failure is a READ's\n * (`error.write === false`) and a retry is always safe:\n *\n * - no answer: `REQUEST_TIMEOUT` / `TRANSPORT_ERROR`, both `write: false` (an app requestor's\n * own rejection passes through unchanged: it is the app's error); a body that broke off is\n * `TRANSPORT_ERROR`;\n * - a numeric top-level `Status` other than 1, in any HTTP status: `GATEWAY_READ_REJECTED`;\n * - any other non-2xx: `GATEWAY_HTTP_ERROR` (`params.status`; the chain's refusal is `error.body`);\n * - a 2xx that is not `{ Status: 1, Data }` (for `GetPublicKey`, whose answer carries no\n * `Status`, not `{ Data }`): `GATEWAY_READ_RESPONSE_INVALID`.\n */\nexport async function readGateway(\n transport: ReadTransport,\n method: GatewayReadMethod,\n body: Record<string, unknown>,\n channel: GatewayChannel = 'asset',\n): Promise<unknown> {\n const url = `${transport.gatewayBaseUrl}/api/${channel}/${CONTRACT_OF[method]}/${method}`;\n const response = await requestWithTimeout(\n transport.requestor,\n url,\n {\n method: 'POST',\n headers: buildRequestHeaders(transport.wire, { json: true }),\n body: JSON.stringify(body),\n },\n transport.timeoutMs,\n { write: false },\n );\n let answer: unknown;\n try {\n answer = await readResponseBody(response);\n } catch (cause: unknown) {\n // The answer's headers arrived and its body broke off: nothing usable was read.\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause, write: false });\n }\n return dataOf(method, url, response, answer);\n}\n\nfunction dataOf(\n method: GatewayReadMethod,\n url: string,\n response: HTTPResponse,\n answer: unknown,\n): unknown {\n const context: GalaErrorContext = { status: response.status, body: answer, url, write: false };\n const envelope = isRecord(answer) ? answer : undefined;\n const chainStatus = envelope?.['Status'];\n if (typeof chainStatus === 'number' && chainStatus !== 1) {\n throw new GalaSDKError(\n 'GATEWAY_READ_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 const chainError = chainErrorOf(answer);\n throw new GalaSDKError(\n 'GATEWAY_HTTP_ERROR',\n {\n method,\n status: response.status,\n serverMessage: stringField(chainError, 'Message') || stringField(envelope, 'message'),\n },\n context,\n );\n }\n const statusAccepted =\n chainStatus === 1 || (chainStatus === undefined && ANSWERED_WITHOUT_STATUS.has(method));\n if (envelope === undefined || !statusAccepted || !('Data' in envelope)) {\n throw new GalaSDKError('GATEWAY_READ_RESPONSE_INVALID', { method }, context);\n }\n return envelope['Data'];\n}\n\n/** The error for a 2xx whose `Data` is not what `method` answers. */\nexport function invalidAnswer(\n method: GatewayReadMethod,\n data: unknown,\n): GalaSDKError<'GATEWAY_READ_RESPONSE_INVALID'> {\n return new GalaSDKError(\n 'GATEWAY_READ_RESPONSE_INVALID',\n { method },\n { body: data, write: false },\n );\n}\n","import type { HttpRequestor } from '../types/http_requestor.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { WireOptions } from '../types/wire.js';\nimport type { TokenClassKeyInput } from '../writes/types.js';\n\n/**\n * The contract methods `GatewayReads` calls, as a closed set: the token-contract reads, and\n * `GetPublicKey` of the public-key-contract.\n */\nexport const GATEWAY_READ_METHODS = [\n 'FetchBalances',\n 'FetchTokenClasses',\n 'FetchTokenClassesWithSupply',\n 'FetchTokenClassesWithPagination',\n 'FetchNftCollectionAuthorizationsWithPagination',\n 'GetPublicKey',\n] as const;\n\n/** One member of {@link GATEWAY_READ_METHODS}. */\nexport type GatewayReadMethod = (typeof GATEWAY_READ_METHODS)[number];\n\n/**\n * The public key GalaChain has registered for a user (`GetPublicKey`), as the chain answers it.\n * `publicKey` is the chain's encoding (base64 of the compressed secp256k1 key); `signing` is the\n * signing scheme older chain versions store next to it (`'ETH'`, `'TON'`), absent on current ones.\n */\nexport interface GalaChainPublicKey {\n readonly publicKey: string;\n readonly signing?: string | undefined;\n}\n\n/**\n * The SDK's bounds on one read: at most `tokenClasses` keys per `fetchTokenClasses` /\n * `fetchTokenClassesWithSupply` request, at most `pageSize` results per page of a paginated read\n * (the chain's own maximum for its paginated token reads), and by default at most `maxPages`\n * pages per `fetchAll...` call.\n */\nexport const GATEWAY_READ_LIMITS = Object.freeze({\n tokenClasses: 1000,\n pageSize: 10_000,\n maxPages: 100,\n});\n\n/** How to reach the gateway for reads. Reads are unsigned: no signer is involved. */\nexport interface GatewayReadsOptions {\n /**\n * The GalaChain gateway base URL; every read POSTs to\n * `<gatewayBaseUrl>/api/<channel>/<contract>/<Method>` (`token-contract`, or\n * `public-key-contract` for `GetPublicKey`). `''` sends the bare path, for an `httpRequestor`\n * that resolves paths against its own base (an HTTP client with a base URL). The public gateways\n * do not route the public-key-contract; a connect-api's `.../galachain` proxy base does.\n */\n gatewayBaseUrl: string;\n /** The HTTP requestor; default the global `fetch`. Its own rejections reach the caller unchanged. */\n httpRequestor?: HttpRequestor | undefined;\n /** Timeout of every read request in milliseconds (default 30 000); `Infinity` arms no timer. */\n requestTimeoutMs?: number | undefined;\n /** Headers of every read request (`userAgent`, `headers`); see {@link WireOptions}. */\n wire?: WireOptions | undefined;\n}\n\n/**\n * A hold on part of a balance (a lock, or the legacy in-use hold), as GalaChain stores it.\n * `quantity` is whole tokens as a decimal string; times are epoch milliseconds.\n */\nexport interface GalaChainTokenHold {\n /** When the hold was placed. */\n readonly created: number;\n /** Who placed it. */\n readonly createdBy: string;\n /** When it expires; `0` means never. */\n readonly expires: number;\n /** The token instance held (`\"0\"` for a fungible token). */\n readonly instanceId: string;\n /** Who may release it. */\n readonly lockAuthority: string;\n /** The hold's name, when it has one. */\n readonly name?: string | undefined;\n /** How much is held, in whole tokens. */\n readonly quantity: string;\n /** Start of a vesting period, when the hold is a vesting hold. */\n readonly vestingPeriodStart?: number | undefined;\n}\n\n/** One balance record of `FetchBalances`: an owner's holding of one token class. */\nexport interface GalaChainTokenBalance extends GalaChainTokenClassKey {\n readonly owner: string;\n /** The holding in whole tokens, as the chain's decimal string (never scaled). */\n readonly quantity: string;\n /** The instance ids held, for a non-fungible token; empty for a fungible one. */\n readonly instanceIds: readonly string[];\n /** Locks on the holding. */\n readonly lockedHolds: readonly GalaChainTokenHold[];\n /** The legacy in-use holds (older balances only). */\n readonly inUseHolds: readonly GalaChainTokenHold[];\n}\n\n/**\n * What `fetchBalances` filters by. `owner` is required (without it the chain answers every\n * owner's balances); the class-key parts narrow the answer. A filter on `$MUSIC` or `MUSIC` is\n * sent to the gateway's `music` channel, where that collection lives; every other to `asset`.\n */\nexport interface BalancesFilter {\n /**\n * An Ethereum account (`eth|<40 hex>`, `0x<40 hex>` or `<40 hex>`, any casing but a wrong\n * EIP-55 checksum; always sent as `eth|<checksummed>`), or a `client|` alias (sent as written).\n * `eth|0x<40 hex>` is not an address form and is refused (`INVALID_ETH_USER_REF_PREFIX`). The\n * answer's records carry the owner as sent.\n */\n owner: string;\n collection?: string | undefined;\n category?: string | undefined;\n type?: string | undefined;\n additionalKey?: string | undefined;\n}\n\n/** `fetchTokenBalance`: one owner's balance of one token class, with its holds summed. */\nexport interface TokenBalanceInput {\n /** The owner (see {@link BalancesFilter.owner}). */\n owner: string;\n /** The token class (pipe string with exactly four parts, `$` composite key, or object). */\n tokenClassKey: TokenClassKeyInput;\n /** Keep holds that have expired (default `false`: an expired hold no longer holds anything). */\n includeExpiredHolds?: boolean | undefined;\n /** The time holds are judged at, in epoch milliseconds (default now). */\n asOf?: number | undefined;\n}\n\n/**\n * An owner's balance of one token class with its holds totalled. Every quantity is whole tokens as\n * a plain decimal string (no exponent), computed exactly (`bignumber.js`), never scaled.\n */\nexport interface GalaChainTokenBalanceSummary {\n readonly owner: string;\n readonly tokenClassKey: GalaChainTokenClassKey;\n /** The whole holding. */\n readonly quantity: string;\n /** The locks still in force (all of them with `includeExpiredHolds`). */\n readonly lockedHolds: readonly GalaChainTokenHold[];\n /** The in-use holds still in force (all of them with `includeExpiredHolds`). */\n readonly inUseHolds: readonly GalaChainTokenHold[];\n /** The sum of `lockedHolds`. */\n readonly lockedQuantity: string;\n /** The sum of `inUseHolds`. */\n readonly inUseQuantity: string;\n /** `quantity - lockedQuantity - inUseQuantity`. */\n readonly availableQuantity: string;\n /** The instance ids held (non-fungible tokens). */\n readonly instanceIds: readonly string[];\n}\n\n/**\n * A token class as GalaChain registers it. Supply figures are whole tokens as the chain's decimal\n * strings (`\"Infinity\"` for an uncapped capacity), never numbers.\n */\nexport interface GalaChainTokenClass extends GalaChainTokenClassKey {\n readonly network: string;\n readonly decimals: number;\n readonly maxSupply: string;\n readonly maxCapacity: string;\n readonly isNonFungible: boolean;\n readonly authorities: readonly string[];\n readonly name: string;\n readonly symbol: string;\n readonly description: string;\n readonly image: string;\n readonly totalBurned: string;\n readonly totalMintAllowance: string;\n readonly totalSupply: string;\n readonly contractAddress?: string | undefined;\n readonly metadataAddress?: string | undefined;\n readonly rarity?: string | undefined;\n readonly quantityLimit?: string | undefined;\n /** Supply figures `FetchTokenClassesWithSupply` adds. */\n readonly knownMintSupply?: string | undefined;\n readonly knownMintAllowanceSupply?: string | undefined;\n}\n\n/** The metadata of a token class an app shows: its key, symbol, decimals, name and image. */\nexport interface GalaChainTokenDetails extends GalaChainTokenClassKey {\n readonly symbol: string;\n readonly decimals: number;\n readonly name: string;\n readonly image: string;\n readonly description: string;\n readonly network: string;\n readonly contractAddress?: string | undefined;\n}\n\n/** What `fetchTokenClassesPage` / `fetchAllTokenClasses` filter by (any subset of a class key). */\nexport interface TokenClassesFilter {\n collection?: string | undefined;\n category?: string | undefined;\n type?: string | undefined;\n additionalKey?: string | undefined;\n}\n\n/** One page request of a paginated read. */\nexport interface PageInput {\n /** The `nextPageBookmark` of the previous page; omitted for the first page. */\n bookmark?: string | undefined;\n /** Results per page, 1 to `GATEWAY_READ_LIMITS.pageSize`; omitted: the chain's default. */\n limit?: number | undefined;\n}\n\n/** One page of a paginated read. */\nexport interface GalaChainPage<T> {\n readonly results: readonly T[];\n /** The bookmark of the next page, `undefined` on the last page. */\n readonly nextPageBookmark: string | undefined;\n}\n\n/** How a `fetchAll...` read walks the pages. */\nexport interface AllPagesOptions {\n /** Results per page (see {@link PageInput.limit}). */\n pageSize?: number | undefined;\n /**\n * The most pages it reads, 1 to 10 000 (default `GATEWAY_READ_LIMITS.maxPages`). A data set\n * with more pages is `PAGINATION_LIMIT_EXCEEDED`, never a silently truncated answer.\n */\n maxPages?: number | undefined;\n}\n\n/** Who may create token classes in an NFT collection. */\nexport interface GalaChainNftCollectionAuthorization {\n readonly collection: string;\n readonly authorizedUsers: readonly string[];\n}\n","import BigNumber from 'bignumber.js';\nimport { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport { compositeKeyOf } from '../utils/class_key.js';\nimport { fetchRequestor, validateTimeoutMs } from '../utils/transport.js';\nimport { galaChainUserRef } from '../writes/identity.js';\nimport { tokenClassKeyOf } from '../writes/token_ref.js';\nimport type { TokenClassKeyInput } from '../writes/types.js';\nimport {\n parseBalances,\n parseNftCollectionAuthorization,\n parsePage,\n parsePublicKey,\n parseTokenClass,\n parseTokenClasses,\n} from './parse.js';\nimport {\n channelOf,\n chainErrorOf,\n invalidAnswer,\n readGateway,\n type ReadTransport,\n} from './request.js';\nimport {\n GATEWAY_READ_LIMITS,\n type AllPagesOptions,\n type BalancesFilter,\n type GalaChainNftCollectionAuthorization,\n type GalaChainPage,\n type GalaChainPublicKey,\n type GalaChainTokenBalance,\n type GalaChainTokenBalanceSummary,\n type GalaChainTokenClass,\n type GalaChainTokenDetails,\n type GalaChainTokenHold,\n type GatewayReadMethod,\n type GatewayReadsOptions,\n type PageInput,\n type TokenBalanceInput,\n type TokenClassesFilter,\n} from './types.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\nconst MAX_PAGES_LIMIT = 10_000;\nconst KEY_PARTS = ['collection', 'category', 'type', 'additionalKey'] as const;\n\n/** The class-key parts a filter names, checked (each present one a non-empty string), in key order. */\nfunction filterParts(\n filter: Readonly<Record<string, unknown>>,\n at: string,\n): Partial<GalaChainTokenClassKey> {\n const parts: Partial<Record<(typeof KEY_PARTS)[number], string>> = {};\n for (const part of KEY_PARTS) {\n const value = filter[part];\n if (value === undefined) continue;\n if (typeof value !== 'string' || value === '') {\n throw new GalaSDKError('INVALID_TOKEN_REFERENCE', {\n field: `${at}${part}`,\n reason: 'bad_class_key',\n });\n }\n parts[part] = value;\n }\n return parts;\n}\n\n/** A page size or page count: a whole number from 1 to `max`, or `undefined` for the default. */\nfunction boundedCount(\n value: unknown,\n field: 'limit' | 'pageSize' | 'maxPages',\n max: number,\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 && value <= max) {\n return value;\n }\n // A number or string is shown as written; anything else by its type (never an object's text).\n const shown =\n typeof value === 'number' || typeof value === 'string'\n ? String(value)\n : value === null\n ? 'null'\n : typeof value;\n throw new GalaSDKError('INVALID_PAGE_REQUEST', { field, value: shown });\n}\n\nfunction sameKey(row: GalaChainTokenClassKey, key: GalaChainTokenClassKey): boolean {\n return KEY_PARTS.every((part) => row[part] === key[part]);\n}\n\n/**\n * The metadata an app shows for a token, from its token class: the key, symbol, decimals, name,\n * image, description, network and (when the class has one) contract address. A class key never\n * carries a symbol; this is where one comes from.\n */\nexport function tokenDetailsOf(tokenClass: GalaChainTokenClass): GalaChainTokenDetails {\n return {\n collection: tokenClass.collection,\n category: tokenClass.category,\n type: tokenClass.type,\n additionalKey: tokenClass.additionalKey,\n symbol: tokenClass.symbol,\n decimals: tokenClass.decimals,\n name: tokenClass.name,\n image: tokenClass.image,\n description: tokenClass.description,\n network: tokenClass.network,\n ...(tokenClass.contractAddress === undefined\n ? {}\n : { contractAddress: tokenClass.contractAddress }),\n };\n}\n\n/** The amount of `holds` together, exactly, as a plain decimal string. */\nfunction totalOf(holds: readonly GalaChainTokenHold[]): BigNumber {\n return holds.reduce((sum, hold) => sum.plus(hold.quantity), new BigNumber(0));\n}\n\n/**\n * Unsigned GalaChain token-contract reads through the gateway: balances (with their holds summed),\n * token classes (with or without supply, by key or page by page), token metadata and NFT\n * collection authorizations; and a user's registered public key (public-key-contract). React\n * Native safe (no Node builtins, no ethers, no `@gala-chain/api`).\n *\n * Every input is checked before anything is sent (owners as `GatewayWrites` spells them, class\n * keys in the forms a write accepts, page sizes), and every answer is checked before it is\n * trusted: GalaChain's `Status`, then each row's shape. Amounts stay the chain's whole-token\n * decimal strings (never scaled, never numbers). A read applies nothing, so a retry is always\n * safe: every failure after the request left says so (`error.write === false`), and an input\n * refused before it is `pre_send` (nothing was sent).\n *\n * @example\n * ```ts\n * const reads = new GatewayReads({ gatewayBaseUrl: 'https://gateway-mainnet.galachain.com' });\n * const gala = await reads.fetchTokenBalance({ owner: 'client|abc', tokenClassKey: 'GALA|Unit|none|none' });\n * console.log(gala?.availableQuantity);\n * ```\n */\nexport class GatewayReads {\n private readonly transport: ReadTransport;\n\n /**\n * @throws GalaSDKError `INVALID_READS_OPTION` (a missing base URL, a requestor that is not a\n * function), `INVALID_TIMEOUT`.\n */\n constructor(options: GatewayReadsOptions) {\n const { gatewayBaseUrl, httpRequestor } = options;\n if (typeof gatewayBaseUrl !== 'string') {\n throw new GalaSDKError('INVALID_READS_OPTION', { option: 'gatewayBaseUrl' });\n }\n if (httpRequestor !== undefined && typeof httpRequestor !== 'function') {\n throw new GalaSDKError('INVALID_READS_OPTION', { option: 'httpRequestor' });\n }\n this.transport = {\n gatewayBaseUrl: gatewayBaseUrl.replace(/\\/+$/u, ''),\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 * The owner's balance records (`FetchBalances`), narrowed by any class-key parts given. Sent to\n * the `music` channel for `$MUSIC`, else `asset`. An answer with a record of another owner is\n * `GATEWAY_READ_RESPONSE_INVALID` (it is never reported as the owner's).\n *\n * @throws GalaSDKError pre-send: `INVALID_WALLET_ADDRESS` (`field: 'owner'`),\n * `INVALID_TOKEN_REFERENCE`; then the read failures (see the class note).\n */\n public async fetchBalances(filter: BalancesFilter): Promise<GalaChainTokenBalance[]> {\n const owner = galaChainUserRef(filter.owner, 'owner');\n const parts = filterParts(filter as unknown as Record<string, unknown>, '');\n const data = await readGateway(\n this.transport,\n 'FetchBalances',\n { owner, ...parts },\n channelOf(parts.collection),\n );\n const balances = parseBalances(data);\n // A record of anyone but the owner asked for is never reported as theirs.\n if (balances === undefined || balances.some((row) => row.owner !== owner)) {\n throw invalidAnswer('FetchBalances', data);\n }\n return balances;\n }\n\n /**\n * The owner's balance of one token class with its holds totalled, or `undefined` when the chain\n * has no balance record of it for the owner. Holds that have expired are dropped (they no longer\n * hold anything) unless `includeExpiredHolds`.\n *\n * @throws GalaSDKError as {@link fetchBalances}.\n */\n public async fetchTokenBalance(\n input: TokenBalanceInput,\n ): Promise<GalaChainTokenBalanceSummary | undefined> {\n const key = tokenClassKeyOf(input.tokenClassKey, 'tokenClassKey');\n const balance = (await this.fetchBalances({ owner: input.owner, ...key })).find((row) =>\n sameKey(row, key),\n );\n if (balance === undefined) return undefined;\n const now = Date.now();\n const inForce = (holds: readonly GalaChainTokenHold[]): GalaChainTokenHold[] =>\n input.includeExpiredHolds === true\n ? [...holds]\n : holds.filter((hold) => hold.expires === 0 || hold.expires > now);\n const lockedHolds = inForce(balance.lockedHolds);\n const inUseHolds = inForce(balance.inUseHolds);\n const locked = totalOf(lockedHolds);\n const inUse = totalOf(inUseHolds);\n return {\n owner: balance.owner,\n tokenClassKey: key,\n quantity: balance.quantity,\n lockedHolds,\n inUseHolds,\n lockedQuantity: locked.toFixed(),\n inUseQuantity: inUse.toFixed(),\n availableQuantity: new BigNumber(balance.quantity).minus(locked).minus(inUse).toFixed(),\n instanceIds: balance.instanceIds,\n };\n }\n\n /**\n * The owner's non-fungible holdings: the balance records that hold at least one instance.\n *\n * @throws GalaSDKError as {@link fetchBalances}.\n */\n public async fetchNftBalances(filter: BalancesFilter): Promise<GalaChainTokenBalance[]> {\n return (await this.fetchBalances(filter)).filter((row) => row.instanceIds.length > 0);\n }\n\n /**\n * The token classes of `tokenClassKeys` (`FetchTokenClasses`), one per key, in the order asked.\n *\n * @throws GalaSDKError pre-send: `INVALID_TOKEN_BATCH` (1 to `GATEWAY_READ_LIMITS.tokenClasses`\n * keys), `INVALID_TOKEN_REFERENCE`; `TOKEN_CLASS_NOT_FOUND` for a key the chain has no class\n * of; then the read failures.\n */\n public fetchTokenClasses(\n tokenClassKeys: readonly TokenClassKeyInput[],\n ): Promise<GalaChainTokenClass[]> {\n return this.readClasses('FetchTokenClasses', tokenClassKeys);\n }\n\n /**\n * As {@link fetchTokenClasses}, with the chain's supply figures (`knownMintSupply`,\n * `knownMintAllowanceSupply`) on each class (`FetchTokenClassesWithSupply`).\n */\n public fetchTokenClassesWithSupply(\n tokenClassKeys: readonly TokenClassKeyInput[],\n ): Promise<GalaChainTokenClass[]> {\n return this.readClasses('FetchTokenClassesWithSupply', tokenClassKeys);\n }\n\n /**\n * The token class of one key.\n *\n * @throws GalaSDKError as {@link fetchTokenClasses}.\n */\n public async fetchTokenClass(tokenClassKey: TokenClassKeyInput): Promise<GalaChainTokenClass> {\n const [tokenClass] = await this.readClasses('FetchTokenClasses', [tokenClassKey]);\n return tokenClass as GalaChainTokenClass;\n }\n\n /**\n * The metadata an app shows for a token (its key, symbol, decimals, name, image, description,\n * network and contract address), from its token class: the source of truth for a symbol, which\n * a class key never carries.\n *\n * @throws GalaSDKError as {@link fetchTokenClasses}.\n */\n public async fetchTokenDetails(\n tokenClassKey: TokenClassKeyInput,\n ): Promise<GalaChainTokenDetails> {\n return tokenDetailsOf(await this.fetchTokenClass(tokenClassKey));\n }\n\n /**\n * One page of the token classes matching `filter` (`FetchTokenClassesWithPagination`).\n *\n * @throws GalaSDKError pre-send: `INVALID_TOKEN_REFERENCE`, `INVALID_PAGE_REQUEST`; then the\n * read failures.\n */\n public async fetchTokenClassesPage(\n filter: TokenClassesFilter & PageInput = {},\n ): Promise<GalaChainPage<GalaChainTokenClass>> {\n const parts = filterParts(filter as unknown as Record<string, unknown>, '');\n return this.readPage('FetchTokenClassesWithPagination', parts, filter, parseTokenClass);\n }\n\n /**\n * Every token class matching `filter`, page by page, up to `maxPages` pages.\n *\n * @throws GalaSDKError as {@link fetchTokenClassesPage}, plus `PAGINATION_LIMIT_EXCEEDED`.\n */\n public async fetchAllTokenClasses(\n filter: TokenClassesFilter = {},\n options: AllPagesOptions = {},\n ): Promise<GalaChainTokenClass[]> {\n const parts = filterParts(filter as unknown as Record<string, unknown>, '');\n return this.readAllPages('FetchTokenClassesWithPagination', options, (page) =>\n this.readPage('FetchTokenClassesWithPagination', parts, page, parseTokenClass),\n );\n }\n\n /**\n * One page of the NFT collection authorizations (`FetchNftCollectionAuthorizationsWithPagination`):\n * which users may create token classes in which collection.\n *\n * @throws GalaSDKError pre-send: `INVALID_PAGE_REQUEST`; then the read failures.\n */\n public fetchNftCollectionAuthorizationsPage(\n page: PageInput = {},\n ): Promise<GalaChainPage<GalaChainNftCollectionAuthorization>> {\n return this.readPage(\n 'FetchNftCollectionAuthorizationsWithPagination',\n {},\n page,\n parseNftCollectionAuthorization,\n );\n }\n\n /**\n * Every NFT collection authorization, page by page, up to `maxPages` pages.\n *\n * @throws GalaSDKError as {@link fetchNftCollectionAuthorizationsPage}, plus\n * `PAGINATION_LIMIT_EXCEEDED`.\n */\n public fetchAllNftCollectionAuthorizations(\n options: AllPagesOptions = {},\n ): Promise<GalaChainNftCollectionAuthorization[]> {\n return this.readAllPages('FetchNftCollectionAuthorizationsWithPagination', options, (page) =>\n this.fetchNftCollectionAuthorizationsPage(page),\n );\n }\n\n /**\n * The public key GalaChain has registered for `user` (`GetPublicKey` of the\n * public-key-contract, `asset` channel), or `undefined` when the chain has none saved for that\n * user (its `PK_NOT_FOUND`). The public gateways do not route this contract: build the reads with\n * a connect-api `.../galachain` proxy base (`https://<connect-api>/galachain`), whose answer is\n * `{ Data: { publicKey } }` without a `Status` (a `Status` that is sent is still checked).\n *\n * @example\n * ```ts\n * const reads = new GatewayReads({ gatewayBaseUrl: 'https://api-galaswap.gala.com/galachain' });\n * const registered = await reads.fetchPublicKey('client|64f8caf887fd8551315d8509');\n * console.log(registered?.publicKey);\n * ```\n *\n * @throws GalaSDKError pre-send: `INVALID_WALLET_ADDRESS` (`field: 'user'`); then the read\n * failures (see the class note).\n */\n public async fetchPublicKey(user: string): Promise<GalaChainPublicKey | undefined> {\n const ref = galaChainUserRef(user, 'user');\n let data: unknown;\n try {\n data = await readGateway(this.transport, 'GetPublicKey', { user: ref });\n } catch (error: unknown) {\n if (isPublicKeyNotFound(error)) return undefined;\n throw error;\n }\n const publicKey = parsePublicKey(data);\n if (publicKey === undefined) throw invalidAnswer('GetPublicKey', data);\n return publicKey;\n }\n\n private async readClasses(\n method: 'FetchTokenClasses' | 'FetchTokenClassesWithSupply',\n tokenClassKeys: readonly TokenClassKeyInput[],\n ): Promise<GalaChainTokenClass[]> {\n const count = Array.isArray(tokenClassKeys) ? tokenClassKeys.length : 0;\n const max = GATEWAY_READ_LIMITS.tokenClasses;\n if (count < 1 || count > max) {\n throw new GalaSDKError('INVALID_TOKEN_BATCH', { method, count, max });\n }\n const keys = tokenClassKeys.map((key, index) =>\n tokenClassKeyOf(key, `tokenClassKeys[${index}]`),\n );\n let data: unknown;\n try {\n data = await readGateway(this.transport, method, { tokenClasses: keys });\n } catch (error: unknown) {\n throw notFoundOf(error) ?? error;\n }\n const rows = parseTokenClasses(data);\n if (rows === undefined) throw invalidAnswer(method, data);\n return keys.map((key) => {\n const row = rows.find((candidate) => sameKey(candidate, key));\n if (row === undefined) {\n throw new GalaSDKError(\n 'TOKEN_CLASS_NOT_FOUND',\n { tokenClassKey: compositeKeyOf(key) },\n { body: data, write: false },\n );\n }\n return row;\n });\n }\n\n private async readPage<T>(\n method: GatewayReadMethod,\n parts: Partial<GalaChainTokenClassKey>,\n page: PageInput,\n parse: (entry: unknown) => T | undefined,\n ): Promise<GalaChainPage<T>> {\n const limit = boundedCount(page.limit, 'limit', GATEWAY_READ_LIMITS.pageSize);\n const { bookmark } = page;\n if (bookmark !== undefined && typeof bookmark !== 'string') {\n throw new GalaSDKError('INVALID_PAGE_REQUEST', { field: 'bookmark', value: typeof bookmark });\n }\n const data = await readGateway(this.transport, method, {\n ...parts,\n ...(bookmark === undefined || bookmark === '' ? {} : { bookmark }),\n ...(limit === undefined ? {} : { limit }),\n });\n const parsed = parsePage(data, parse);\n if (parsed === undefined) throw invalidAnswer(method, data);\n return parsed;\n }\n\n /**\n * Reads page after page until the chain says there is none left. Bounded: a page whose bookmark\n * does not move on is an unusable answer (it would repeat forever), and a data set with more\n * than `maxPages` pages is `PAGINATION_LIMIT_EXCEEDED`, never a truncated list.\n */\n private async readAllPages<T>(\n method: GatewayReadMethod,\n options: AllPagesOptions,\n readPage: (page: PageInput) => Promise<GalaChainPage<T>>,\n ): Promise<T[]> {\n const maxPages =\n boundedCount(options.maxPages, 'maxPages', MAX_PAGES_LIMIT) ?? GATEWAY_READ_LIMITS.maxPages;\n const limit = boundedCount(options.pageSize, 'pageSize', GATEWAY_READ_LIMITS.pageSize);\n const results: T[] = [];\n let bookmark: string | undefined;\n for (let page = 0; page < maxPages; page += 1) {\n const answer = await readPage({\n ...(bookmark === undefined ? {} : { bookmark }),\n ...(limit === undefined ? {} : { limit }),\n });\n results.push(...answer.results);\n if (answer.nextPageBookmark === undefined) return results;\n if (answer.nextPageBookmark === bookmark) throw invalidAnswer(method, answer);\n bookmark = answer.nextPageBookmark;\n }\n throw new GalaSDKError('PAGINATION_LIMIT_EXCEEDED', { method, maxPages }, { write: false });\n }\n}\n\n/** The chain's \"no public key saved for this user\": HTTP 404 with `ErrorKey: PK_NOT_FOUND`. */\nfunction isPublicKeyNotFound(error: unknown): boolean {\n if (!isGalaError(error, 'GATEWAY_HTTP_ERROR') || error.status !== 404) return false;\n return chainErrorOf(error.body)?.['ErrorKey'] === 'PK_NOT_FOUND';\n}\n\n/**\n * The chain's \"no such token class\" (HTTP 404, `ErrorKey: TOKEN_CLASS_NOT_FOUND`) as\n * `TOKEN_CLASS_NOT_FOUND`, naming the key the chain named; `undefined` for any other failure.\n */\nfunction notFoundOf(error: unknown): GalaSDKError<'TOKEN_CLASS_NOT_FOUND'> | undefined {\n if (!isGalaError(error, 'GATEWAY_HTTP_ERROR') || error.status !== 404) return undefined;\n const chainError = chainErrorOf(error.body);\n if (chainError?.['ErrorKey'] !== 'TOKEN_CLASS_NOT_FOUND') return undefined;\n const payload = chainError['ErrorPayload'];\n const named =\n typeof payload === 'object' && payload !== null\n ? (payload as Record<string, unknown>)['tokenClassKey']\n : undefined;\n return new GalaSDKError(\n 'TOKEN_CLASS_NOT_FOUND',\n { tokenClassKey: typeof named === 'string' ? named : '' },\n { status: error.status, body: error.body, url: error.url, write: false, cause: error },\n );\n}\n","/** A GalaChain deployment: `prod` (mainnet) or `stage` (testnet). */\nexport type GalaChainEnv = 'prod' | 'stage';\n\n/** The product-independent endpoints of one GalaChain deployment. */\nexport interface GalaChainEnvironmentConfig {\n /** The public GalaChain gateway (`GatewayReads` / `GatewayWrites` `gatewayBaseUrl`). */\n readonly gatewayBaseUrl: string;\n /** The DEX API platform (GalaConnect: bridge, wrap and referral reads). */\n readonly dexApiBaseUrl: string;\n /**\n * The EIP-712 domain NAME the deployment's chain requires of a typed-data signature\n * (\"EIP-712 domain name must be GalaChainStage for this deployment. Received ethereum.\"). Pass\n * it to a signer's `eip712DomainName` option. Absent where the deployment accepts the name each\n * signer has always used (`prod`), so a signer given `undefined` signs exactly what it always\n * did.\n */\n readonly eip712DomainName?: string;\n}\n\n/**\n * The built-in endpoints of each deployment. A product SDK extends these with its own backends\n * (launchpad-sdk's launchpad and bundler URLs, gswap-sdk's swap backend); it never redefines them.\n */\nexport const GALA_CHAIN_ENVIRONMENTS: Readonly<Record<GalaChainEnv, GalaChainEnvironmentConfig>> =\n Object.freeze({\n prod: Object.freeze({\n gatewayBaseUrl: 'https://gateway-mainnet.galachain.com',\n dexApiBaseUrl: 'https://dex-api-platform-dex-prod-gala.gala.com',\n }),\n stage: Object.freeze({\n gatewayBaseUrl: 'https://gateway-testnet.galachain.com',\n dexApiBaseUrl: 'https://dex-api-platform-dex-stage-gala.gala.com',\n eip712DomainName: 'GalaChainStage',\n }),\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;AACF;;;;;;;;;;;AAeA,MAAa,0BAA0B,CAAC,iBAAiB,QAAQ;;;;;;;;;;;;;AAiBjE,MAAa,kCAAkC;CAC7C;CACA;CACA;CACA;AACF;;;;;;;AAWA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;AACF;;;;;;;;;;AAcA,MAAa,wCAAwC,CAAC,WAAW,WAAW;;;;;AAU5E,MAAa,wBAAwB,CAAC,kBAAkB,eAAe;;;;;;;;AAYvE,MAAa,sBAAsB;CAAC;CAAS;CAAY;CAAY;AAAU;;;;;;;;;;AAc/E,MAAa,+BAA+B;CAC1C;CACA;CACA;AACF;;;;;;;;AAYA,MAAa,oCAAoC;CAC/C;CACA;CACA;AACF;;;;;;;;AAYA,MAAa,iCAAiC,CAC5C,oBACA,iCACF;;;;;;;;;;;AAeA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;AACF;;AAMA,MAAa,kBAAkB,CAAC,YAAY,QAAQ;;;;;;;;AAYpD,MAAa,yBAAyB;CACpC;CACA;CACA;AACF;;;;;;;;;AAaA,MAAa,mBAAmB;CAAC;CAAc;CAAoB;AAAkB;;;;;;;;AAYrF,MAAa,uBAAuB;CAAC;CAAQ;CAAgB;AAAc;;;;;;;;AAY3E,MAAa,uBAAuB;CAAC;CAAc;CAAkB;AAAiB;;AAMtF,MAAa,kBAAkB,CAAC,QAAQ,QAAQ;;AAMhD,MAAa,qBAAqB;CAEhC,iBAAiB;EACf,OAAO;EACP,UAAU;EACV,QAAQ;GAAE,KAAK;GAAU,WAAW;EAAS;CAC/C;CACA,iBAAiB;EACf,OAAO;EACP,UAA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