@gala-chain/gala-core-sdk 1.0.0-rc.7 → 1.0.0-rc.8

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.
package/README.md CHANGED
@@ -7,7 +7,7 @@ timeouts, wire options, axios and ethers adapters), the gateway token reads (bal
7
7
  token classes, NFT collection authorizations) and writes (transfer, burn, lock, unlock), token
8
8
  class keys and write `uniqueKey`s, and the shared error model (`GalaSDKError`, its
9
9
  catalog, the failure view). It speaks to the GalaChain
10
- gateway generically; product backends (dex-backend, launchpad-backend) have their own SDKs
10
+ gateway generically; product backends (the DEX and Launchpad backends) have their own SDKs
11
11
  (`@gala-chain/gswap-sdk`, `@gala-chain/launchpad-sdk`) that build on it.
12
12
 
13
13
  ## Install
@@ -43,7 +43,6 @@ key.fill(0);
43
43
  | Transport | `fetchRequestor`, `requestWithTimeout` (`kind: { write: false }` makes a read's timeout and transport failure say `write: false`), `buildRequestHeaders`, `buildQueryString`, `readRetryAfter`, `httpRequestorFromAxios`, `eip1193ProviderFromEthers`, `isFetchTransportFailure`, types `HttpRequestor`, `WireOptions`, `RequestKind` |
44
44
  | Gateway reads | `GatewayReads` (`fetchBalances`, `fetchTokenBalance`, `fetchNftBalances`, `fetchTokenClasses`, `fetchTokenClassesWithSupply`, `fetchTokenClass`, `fetchTokenDetails`, `fetchTokenClassesPage`, `fetchAllTokenClasses`, `fetchNftCollectionAuthorizationsPage`, `fetchAllNftCollectionAuthorizations`, `fetchPublicKey`), `GATEWAY_READ_METHODS`, `GATEWAY_READ_LIMITS`, types `GalaChainTokenBalance`, `GalaChainTokenBalanceSummary`, `GalaChainTokenClass`, `GalaChainTokenDetails`, `GalaChainPage`, `GalaChainPublicKey` |
45
45
  | Gateway writes | `GatewayWrites` (`transferGala`, `transferToken`, `burnTokens`, `lockTokens`, `unlockTokens`), `galaChainUserRef` (a user reference in the one spelling the gateway accepts), `GATEWAY_WRITE_METHODS`, `GATEWAY_WRITE_BATCH_LIMITS`, `GALA_TOKEN_CLASS_KEY`, types `GatewayWritesOptions`, `GatewayWriteReceipt`, `TokenNameResolver`, `TokenQuantityInput` |
46
- | Gateway reads | `GatewayReads` (`fetchBalances`, `fetchTokenBalance`, `fetchNftBalances`, `fetchTokenClasses`, `fetchTokenClassesWithSupply`, `fetchTokenClass`, `fetchTokenDetails`, `fetchTokenClassesPage`, `fetchAllTokenClasses`, `fetchNftCollectionAuthorizationsPage`, `fetchAllNftCollectionAuthorizations`, `fetchPublicKey`), `GATEWAY_READ_METHODS`, `GATEWAY_READ_LIMITS`, types `GalaChainTokenBalance`, `GalaChainTokenBalanceSummary`, `GalaChainTokenClass`, `GalaChainTokenDetails`, `GalaChainPage`, `GalaChainPublicKey` |
47
46
  | Deployments | `GALA_CHAIN_ENVIRONMENTS` (gateway and DEX API of `prod` / `stage`) |
48
47
  | Keys | `compositeKeyOf`, `tryParseTokenClassKey`, `tryParseCompositeKey`, `createUniqueKey`, `assertUniqueKey`, `isValidUniqueKey` |
49
48
  | Wallets | `createWallet` (random, from a private key, or from a 12/24-word mnemonic at `m/44'/60'/0'/0/0`), `validateWalletInput`, `getPublicKeyFromPrivateKey`, `getEthereumAddressFromPrivateKey`, `checksumEthereumAddress`, types `GeneratedWallet`, `PublicKeyResult` |
@@ -110,7 +109,9 @@ TypeScript 6, `"types": ["node"]`) or `skipLibCheck`. The other entries need no
110
109
  import { detectWallets, ExternalWalletProvider, PrivateKeyProvider } from '@gala-chain/gala-core-sdk/providers';
111
110
 
112
111
  const { wallets } = await detectWallets(); // EIP-6963 announcements, then window.ethereum / window.gala
113
- const provider = new ExternalWalletProvider(wallets[0].provider);
112
+ const first = wallets[0];
113
+ if (first === undefined) throw new Error('No wallet announced itself');
114
+ const provider = new ExternalWalletProvider(first.provider);
114
115
  await provider.connect();
115
116
  await provider.signMessage('Hello'); // personal_sign
116
117
  const signer = provider.getSigner(); // a GalaChainSigner for GatewayWrites, gswap-sdk, ...
@@ -217,10 +218,10 @@ const classes = await reads.fetchAllTokenClasses({ collection: 'BONKTactics' },
217
218
 
218
219
  ## Signing parity
219
220
 
220
- The signing code is pinned byte-for-byte to `@gala-chain/api`, wallet_extension and frontend_v2 by
221
- the golden vectors in `tests/fixtures/wallet-signing-golden.json` and
222
- `tests/fixtures/frontend-signing-golden.json` (`tests/signing-golden.test.ts`). They are never
223
- regenerated to make a test pass; see gswap-sdk's `SIGNING-PARITY.md` for their provenance.
221
+ The signing code is pinned byte-for-byte to `@gala-chain/api` and to the Gala Wallet's and the
222
+ gSwap web app's signing code by the golden vectors in `tests/fixtures/wallet-signing-golden.json`
223
+ and `tests/fixtures/frontend-signing-golden.json` (`tests/signing-golden.test.ts`). They are never
224
+ regenerated to make a test pass.
224
225
 
225
226
  ## React Native
226
227
 
@@ -255,7 +256,7 @@ gzipped, before `ethers` and `@solana/*`) are loaded only by an app that imports
255
256
 
256
257
  ## Status
257
258
 
258
- 1.0.0-rc.7 (rc.7: `eth|0x<hex>` is refused as `INVALID_ETH_USER_REF_PREFIX`, not an address form; rc.6: `fetchPublicKey`, MetaMask and Trust Wallet detection, silent `restore()`;
259
+ <!-- docs:var version -->1.0.0-rc.8<!-- /docs:var --> (rc.7: `eth|0x<hex>` is refused as `INVALID_ETH_USER_REF_PREFIX`, not an address form; rc.6: `fetchPublicKey`, MetaMask and Trust Wallet detection, silent `restore()`;
259
260
  rc.5: every Ethereum account a read, write or GalaConnect client sends is
260
261
  `eth|<EIP-55>`, the only spelling the gateway accepts, and `galaChainUserRef` is exported; rc.4:
261
262
  `bridgeableTokenService` is required). In: signing, signers, transport and the error model (rc.0, from gswap-sdk); the
@@ -1 +1 @@
1
- {"version":3,"file":"signers.js","names":["globalObject","_defineProperty","getWalletProvider","wallet","GalaSDKError","getNativeSignature","value","getPersonalSignature","ethereumAddressOfAccount","assertNoEthZeroXPrefix","account","match","normalizeEthereumAccount","address","field","normalized","allowGalaPrefix","normalizeGalaWalletAccount","eth","assertWalletIdentity","identity","walletIdentityQueue","withGalaWalletIdentity","setAddress","signWith","run","personalSign","prefix","personalSignPrefixFor","dto","payload","params","methodName","serialize","walletAddress","provider","signEIP712","buildEIP712Payload","domain","eip712DomainFor","fixpointPrefixFor","completedDto","message","eip712Domain","types","PrivateKeySigner","normalizePrivateKey","privateKey","signature","signNative","keyFrom","getPrivateKey","cause","isGalaError","createLazyPrivateKeySigner","expected","options","expectedLower","provided","key","ethAddressOfPrivateKey","GalaWalletSigner","BrowserWalletSigner","EIP712_CAPABLE_METHODS"],"sources":["../../../src/classes/signers.ts"],"sourcesContent":["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 defi-backend's\n// bouncer 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: frontend_v2 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 frontend_v2 keeps\n * in `state.user.wallet` 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): 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.\n const domain = eip712DomainFor(await provider.request({ method: 'eth_chainId', params: [] }));\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 frontend_v2's.\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 frontend_v2's submitted body: ..., 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 wallet build that contains wallet_extension commit 34ca4e4 (strips the embedded `prefix`\n * field and hashes `prefix` + the prefix-less canonical body, the chain's scheme). Wallets\n * released before that fix hash the string with the `prefix` field still inside it and the\n * signature recovers to an address nobody holds, so only opt in once the fixed wallet is\n * released. See SIGNING-PARITY.md.\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 * frontend_v2 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 with wallet_extension commit 34ca4e4.\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 * @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 */\n constructor(\n private readonly provider: BrowserWalletProvider,\n walletAddress: string,\n options: { scheme?: 'personal-sign' | 'eip712' } = {},\n ) {\n this.walletAddress = normalizeEthereumAccount(walletAddress, false);\n this.scheme = options.scheme ?? 'personal-sign';\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\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);\n }\n return personalSign(this.provider, dto, this.walletAddress);\n }\n}\n"],"mappings":"0eAmFA,SAASE,GAAmC,CAE1C,IAAMC,EAASH,WAAa,QAAQ,KACpC,GAAI,CAACG,EACH,MAAM,IAAIC,EAAa,4BAA6B,CAAC,CAAC,EAExD,OAAOD,CACT,CAEA,SAASE,EAAmB,EAAwB,CAMlD,GALI,OAAOC,GAAU,UAKjB,CAAC,6BAA6B,KAAKA,CAAK,EAC1C,MAAM,IAAIF,EAAa,oBAAqB,CAAE,OAAQ,QAAS,CAAC,EAElE,OAAOE,CACT,CAEA,SAASC,EAAqB,EAAwB,CACpD,GAAI,OAAOD,GAAU,UAAY,CAAC,6BAA6B,KAAKA,CAAK,EACvE,MAAM,IAAIF,EAAa,oBAAqB,CAAE,OAAQ,eAAgB,CAAC,EAEzE,OAAOE,CACT,CAiBA,SAAgBE,EAAyB,EAAqC,CAC5EC,EAAuBC,EAAS,SAAS,EACzC,IAAMC,EAAQ,mCAAmC,KAAKD,CAAO,EAC7D,OAAOC,IAAQ,KAAO,IAAA,GAAY,IAAA,GAAY,KAAKA,EAAM,IAC3D,CAEA,SAASC,EACP,EACA,EACA,EAAQ,gBACA,CACRH,EAAuBI,EAASC,CAAK,EACrC,IAAMC,EAAaC,EAAmBR,EAAyBK,CAAO,GAAKA,EAAWA,EACtF,GAAI,CAAC,uBAAuB,KAAKE,CAAU,EACzC,MAAM,IAAIX,EAAa,yBAA0B,CAAE,QAAO,MAAOS,CAAQ,CAAC,EAK5E,OAAOE,CACT,CASA,SAAS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AY,QAAQ,CACnE,CAAC,EACD,MAAO,CAAE,GAAGH,EAAK,UAAWxB,EAAmB2C,CAAS,CAAE,CAC5D,CAAC,CACH,CACF,EASac,EAAb,KAA4D,CAuB1D,YACE,EACA,EACA,EAAmD,CAAC,EACpD,CAHiB,KAAA,SAAA3B,EASHlC,EAAA,KAAA,gBAAA,IAAA,EAAA,EACCA,EAAA,KAAA,SAAA,IAAA,EAAA,EANf,KAAK,cAAgBW,EAAyBsB,EAAe,EAAK,EAClE,KAAK,OAASsB,EAAQ,QAAU,eAClC,CAoBA,WACE,EACA,EACuB,CAIvB,OAHI,KAAK,SAAW,UAAYO,EAAuB,IAAI/B,CAAU,EAC5DI,EAAW,KAAK,SAAUJ,EAAYH,EAAK,KAAK,aAAa,EAE/DH,EAAa,KAAK,SAAUG,EAAK,KAAK,aAAa,CAC5D,CACF"}
1
+ {"version":3,"file":"signers.js","names":["globalObject","_defineProperty","getWalletProvider","wallet","GalaSDKError","getNativeSignature","value","getPersonalSignature","ethereumAddressOfAccount","assertNoEthZeroXPrefix","account","match","normalizeEthereumAccount","address","field","normalized","allowGalaPrefix","normalizeGalaWalletAccount","eth","assertWalletIdentity","identity","walletIdentityQueue","withGalaWalletIdentity","setAddress","signWith","run","personalSign","prefix","personalSignPrefixFor","dto","payload","params","methodName","serialize","walletAddress","provider","signEIP712","buildEIP712Payload","domain","eip712DomainFor","fixpointPrefixFor","completedDto","message","eip712Domain","types","PrivateKeySigner","normalizePrivateKey","privateKey","signature","signNative","keyFrom","getPrivateKey","cause","isGalaError","createLazyPrivateKeySigner","expected","options","expectedLower","provided","key","ethAddressOfPrivateKey","GalaWalletSigner","BrowserWalletSigner","EIP712_CAPABLE_METHODS"],"sources":["../../../src/classes/signers.ts"],"sourcesContent":["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): 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.\n const domain = eip712DomainFor(await provider.request({ method: 'eth_chainId', params: [] }));\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 * @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 */\n constructor(\n private readonly provider: BrowserWalletProvider,\n walletAddress: string,\n options: { scheme?: 'personal-sign' | 'eip712' } = {},\n ) {\n this.walletAddress = normalizeEthereumAccount(walletAddress, false);\n this.scheme = options.scheme ?? 'personal-sign';\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\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);\n }\n return personalSign(this.provider, dto, this.walletAddress);\n }\n}\n"],"mappings":"0eAmFA,SAASE,GAAmC,CAE1C,IAAMC,EAASH,WAAa,QAAQ,KACpC,GAAI,CAACG,EACH,MAAM,IAAIC,EAAa,4BAA6B,CAAC,CAAC,EAExD,OAAOD,CACT,CAEA,SAASE,EAAmB,EAAwB,CAMlD,GALI,OAAOC,GAAU,UAKjB,CAAC,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1 +1 @@
1
- {"version":3,"file":"chain_dto_signing.js","names":["BigNumber","withPrivateKey","key","normalizePrivateKey","privateKey","action","signChainDtoNative","signSerializedNative","serializedDto","signChainDtoHash","signPersonalMessage","prefix","message","PERSONAL_SIGN_LENGTH_PATTERN","isPersonalSignHeader","PERSONAL_SIGN_FORBIDDEN_FIELDS","resolvePersonalSignChainDtoPayload","parsed","data","GalaSDKError","dto","withoutPrefix","forbidden","field","serialize","signChainDtoPersonalSign","signRawObject","rest","obj","\"signature\"","stripEip712DomainType","stripped","typeName","types","tokenClassDollarKey","part","value","token","canonicalDecimalString"],"sources":["../../../src/utils/chain_dto_signing.ts"],"sourcesContent":["/**\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 in\n * `wallet_extension/src/helpers/wallet/signing.ts` (including the fail-closed personal-sign\n * payload resolver from its commit 34ca4e4), 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 defi-backend's bouncer 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 defi-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"],"mappings":"6MA2BA,SAAgBC,EAAkB,EAA6B,EAAmC,CAChG,IAAMC,EAAMC,EAAoBC,CAAU,EAC1C,GAAI,CACF,OAAOC,EAAOH,CAAG,CACnB,QAAU,CACRA,EAAI,KAAK,CAAC,CACZ,CACF,CASA,SAAgBI,EAAmB,EAA6B,EAA+B,CAC7F,OAAOL,EAAeG,EAAa,GAAQG,EAAqBL,EAAKM,CAAa,CAAC,CACrF,CAQA,SAAgBC,EACd,EACA,EACA,EACQ,CACR,OAAOR,EAAeG,EAAa,GAAQM,EAAoBR,EAAKS,EAAQC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AAO,CAAE,GAAGC,CAAI,EAEtB,OADA,OAAOD,EAAKE,UACL,CACL,UAAWvB,EAAmBF,EAAYoB,EAAUG,CAAI,CAAC,EACzD,GAAGA,CACL,CACF,CAMA,SAAgBG,EAAyB,EAA6C,CACpF,IAAMC,EAA8B,CAAC,EACrC,IAAK,IAAMC,KAAY,OAAO,KAAKC,CAAK,EAClCD,IAAa,iBAAgB,EAASA,GAAYC,EAAMD,IAE9D,OAAOD,CACT,CAOA,SAAgBG,EAAoB,EAA2D,CAC7F,IAAMC,EAAQ,GAA0B,CACtC,IAAMC,EAAQC,IAAQd,GACtB,OAAO,OAAOa,GAAU,SAAWA,EAAQ,EAC7C,EACA,MAAO,GAAGD,EAAK,YAAY,EAAE,GAAGA,EAAK,UAAU,EAAE,GAAGA,EAAK,MAAM,EAAE,GAAGA,EAAK,eAAe,GAC1F,CAUA,SAAgBG,EAAuB,EAAgC,CACrE,IAAIrB,EAAS,IAAIjB,EAAU,GAAU,EACrC,GAAI,CACF,EAAS,IAAIA,EAAUoC,CAAK,CAC9B,MAAQ,CAER,CACA,GAAI,CAACnB,EAAO,SAAS,EACnB,MAAM,IAAIE,EAAa,kBAAmB,CAAE,MAAO,OAAOiB,CAAK,CAAE,CAAC,EAEpE,OAAOnB,EAAO,QAAQ,CACxB"}
1
+ {"version":3,"file":"chain_dto_signing.js","names":["BigNumber","withPrivateKey","key","normalizePrivateKey","privateKey","action","signChainDtoNative","signSerializedNative","serializedDto","signChainDtoHash","signPersonalMessage","prefix","message","PERSONAL_SIGN_LENGTH_PATTERN","isPersonalSignHeader","PERSONAL_SIGN_FORBIDDEN_FIELDS","resolvePersonalSignChainDtoPayload","parsed","data","GalaSDKError","dto","withoutPrefix","forbidden","field","serialize","signChainDtoPersonalSign","signRawObject","rest","obj","\"signature\"","stripEip712DomainType","stripped","typeName","types","tokenClassDollarKey","part","value","token","canonicalDecimalString"],"sources":["../../../src/utils/chain_dto_signing.ts"],"sourcesContent":["/**\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"],"mappings":"6MA0BA,SAAgBC,EAAkB,EAA6B,EAAmC,CAChG,IAAMC,EAAMC,EAAoBC,CAAU,EAC1C,GAAI,CACF,OAAOC,EAAOH,CAAG,CACnB,QAAU,CACRA,EAAI,KAAK,CAAC,CACZ,CACF,CASA,SAAgBI,EAAmB,EAA6B,EAA+B,CAC7F,OAAOL,EAAeG,EAAa,GAAQG,EAAqBL,EAAKM,CAAa,CAAC,CACrF,CAQA,SAAgBC,EACd,EACA,EACA,EACQ,CACR,OAAOR,EAAeG,EAAa,GAAQM,EAAoBR,EAAKS,EAAQC,CAAO,CAAC,CACtF,CAEA,MACMC,EAA+B,uBAMrC,SAASC,EAAqB,EAAyB,CACrD,OACEH,EAAO,WAAW;CAAoB,GACtCE,EAA6B,KAAKF,EAAO,MAAM,EAA2B,CAAC,CAE/E,CAQA,MAAMI,EAAiC,CACrC,YACA,WACA,QACA,QACA,SACA,qBACF,EA6BA,SAAgBC,EAAmC,EAA2C,CAC5F,IAAIC,EACJ,GAAI,CACF,EAAS,KAAK,MAAMC,CAAI,CAC1B,MAAQ,CACN,MAAM,IAAIC,EAAa,yBAA0B,CAAC,CAAC,CACrD,CACA,GAAuB,OAAOF,GAAW,WAArCA,GAAiD,MAAM,QAAQA,CAAM,EACvE,MAAM,IAAIE,EAAa,2BAA4B,CAAC,CAAC,EAEvD,IAAMC,E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,GAAGA,EAAK,MAAM,EAAE,GAAGA,EAAK,eAAe,GAC1F,CAUA,SAAgBG,EAAuB,EAAgC,CACrE,IAAIrB,EAAS,IAAIjB,EAAU,GAAU,EACrC,GAAI,CACF,EAAS,IAAIA,EAAUoC,CAAK,CAC9B,MAAQ,CAER,CACA,GAAI,CAACnB,EAAO,SAAS,EACnB,MAAM,IAAIE,EAAa,kBAAmB,CAAE,MAAO,OAAOiB,CAAK,CAAE,CAAC,EAEpE,OAAOnB,EAAO,QAAQ,CACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"eip712.js","names":["generateEIP712Types","types","typeName","fieldsFor","fields","name","addField","fieldValue","type","parentTypeName","onlyGetType","GalaSDKError","key","value","eipType","params","eip712DomainFor","parsed","chainId","EIP712_CAPABLE_METHODS","numericOr0","dto","field","completeAddLiquidityFields","\"positionId\"","completeRemoveLiquidityFields","completeCollectPositionFeesFields","EIP712_FIELD_COMPLETERS","buildEIP712Payload","completer","methodName","completedDto"],"sources":["../../../src/utils/eip712.ts"],"sourcesContent":["/**\n * Genuine EIP-712 typed-data signing for the four v2 dex-contract operations proven (2026-09-16,\n * live bisection against stage — see defi-backend's `chain-findings-artifact` memory /\n * https://claude.ai/artifact/3N9MevSjoQdU7gqnVB3dfU) to recover the `client|` identity correctly\n * via `eth_signTypedData_v4`, unlike `personal_sign` (which only ever resolves the bare `eth|`\n * form — see `BrowserWalletSigner`'s own doc comment). Mirrors frontend_v2's\n * `src/Services/eip712Types.ts` + `readWriteUtilsV2.ts`'s `EIP712_FIELD_COMPLETERS` exactly —\n * ported here rather than shared as a package because the SDKs have no frontend_v2 dependency\n * and should not gain one for four small functions. (Moved from gswap-sdk with the rest of the\n * signing closure; the 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, exactly like frontend_v2\n * (DEFI-1895): a wallet hashes whatever domain it is handed, and MetaMask refuses a `chainId` that\n * differs from its active network, so a hardcoded `1` breaks every wallet that is not on Mainnet.\n * defi-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 * @throws GalaSDKError (`INVALID_CHAIN_ID`) when the wallet answers with anything else.\n */\nexport function eip712DomainFor(chainId: unknown): 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: 'ethereum', 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"],"mappings":"4DAyBA,SAAgBA,EACd,EACA,EACa,CACb,IAAMC,EAAqB,CAAC,EAC5B,EAAMC,GAAY,CAAC,EAOnB,SAASC,EAAU,EAAqD,CACtE,IAAMC,EAASH,EAAMI;;AAErB,GAAI,CAACD,EAAQ,MAAU,MAAM,uCAAuCC,GAAM,EAC1E,OAAOD,CACT,CAEA,SAASE,EACP,EACA,EACA,EACA,EAAc,GACM,CACpB,GAAI,MAAM,Q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AAoB,CACzC,QACE,OAAOO,GAAY,UAAY,OAAOA,GAAY,SAC9C,OAAOA,CAAO,EACd,OAAOA,CACf,CAAC,EAEH,MAAO,CAAE,KAAM,WAAY,QAASD,CAAO,CAC7C,CAUA,MAAaE,kBAA8C,IAAI,IAAI,CACjE,eACA,eACA,kBACA,qBACF,CAAC,EAcD,SAASC,EAAW,EAA8B,EAAuB,CACvE,OAAO,OAAOC,EAAIC,IAAW,SAAWD,EAAIC,GAAS,CACvD,CAUA,SAASC,EAA2B,EAAuD,CACzF,MAAO,CACL,GAAGF,EACH,eAAgBD,EAAWC,EAAK,gBAAgB,EAChD,WAAYD,EAAWC,EAAK,YAAY,EACxC,eAAgBD,EAAWC,EAAK,gBAAgB,EAChD,WAAYD,EAAWC,EAAK,YAAY,EACxC,WAAYA,EAAIG,YAAiB,EACnC,CACF,CASA,SAASC,EAA8B,EAAuD,CAC5F,MAAO,CACL,GAAGJ,EACH,OAAQD,EAAWC,EAAK,QAAQ,EAChC,WAAYD,EAAWC,EAAK,YAAY,EACxC,WAAYD,EAAWC,EAAK,YAAY,EACxC,WAAYA,EAAIG,YAAiB,EACnC,CACF,CAOA,SAASE,EAAkC,EAAuD,CAChG,MAAO,CACL,GAAGL,EACH,iBAAkBD,EAAWC,EAAK,kBAAkB,EACpD,iBAAkBD,EAAWC,EAAK,kBAAkB,EACpD,WAAYA,EAAIG,YAAiB,EACnC,CACF,CAEA,MAAaG,EAET,CACF,aAAcJ,EACd,gBAAiBE,EACjB,oBAAqBC,CACvB,EAOA,SAAgBE,EACd,EACA,EAC+D,CAC/D,IAAMC,EAAYF,EAAwBG,GACpCC,EAAeF,EAAYA,EAAUR,CAAG,EAAIA,EAElD,MAAO,CAAE,eAAc,MADTrB,EAAoB8B,EAAYC,CACnB,CAAE,CAC/B"}
1
+ {"version":3,"file":"eip712.js","names":["generateEIP712Types","types","typeName","fieldsFor","fields","name","addField","fieldValue","type","parentTypeName","onlyGetType","GalaSDKError","key","value","eipType","params","eip712DomainFor","parsed","chainId","EIP712_CAPABLE_METHODS","numericOr0","dto","field","completeAddLiquidityFields","\"positionId\"","completeRemoveLiquidityFields","completeCollectPositionFeesFields","EIP712_FIELD_COMPLETERS","buildEIP712Payload","completer","methodName","completedDto"],"sources":["../../../src/utils/eip712.ts"],"sourcesContent":["/**\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 * @throws GalaSDKError (`INVALID_CHAIN_ID`) when the wallet answers with anything else.\n */\nexport function eip712DomainFor(chainId: unknown): 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: 'ethereum', 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"],"mappings":"4DAsBA,SAAgBA,EACd,EACA,EACa,CACb,IAAMC,EAAqB,CAAC,EAC5B,EAAMC,GAAY,CAAC,EAOnB,SAASC,EAAU,EAAqD,CACtE,IAAMC,EAASH,EAAMI;;AAErB,GAAI,CAACD,EAAQ,MAAU,MAAM,uCAAuCC,GAAM,EAC1E,OAAOD,CACT,CAEA,SAASE,EACP,EACA,EACA,EACA,EAAc,GACM,CACpB,GAAI,MAAM,QAAQC,CAAU,EAAG,CAC7B,IAAMC,EACJD,EAAW,OAAS,EAAID,EAASD,EAAME,EAAW,GAAIE,EAAgB,EAAI,EAAI,SAC3EC,GAAaP,EAAUM,CAAc,CAAC,CAAC,KAAK,CAAE,OAAM,MAAOD,GAAQH,GAAQ,IAAK,CAAC,CACxF,MAAO,GAAI,OAAOE,GAAe,UAAYA,EAAqB,CAChE,GAAIN,EAAMI,GACR,MAAM,IAAIM,EAAa,wBAAyB,CAAE,MAAK,CAAC,EAE1D,EAAMN,GAAQ,CAAC,EACf,OAAO,QAAQE,CAAU,CAAC,CAAC,SAAS,CAACK,EAAKC,KAAW,CACnDP,EAASM,EAAKC,EAAOR,CAAI,CAC3B,CAAC,EACIK,GAAaP,EAAUM,CAAc,CAAC,CAAC,KAAK,CAAE,OAAM,KAAMJ,CAAK,CAAC,CACvE,KAAO,CACL,IAAIS,EACJ,OAAQ,OAAOP,EAAf,CACE,IAAK,SACH,EAAU,SACV,MACF,IAAK,SACH,EAAU,SACV,MACF,IAAK,UACH,EAAU,OACV,MACF,IAAK,SAC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K,YAAY,EACxC,WAAYA,EAAIG,YAAiB,EACnC,CACF,CAOA,SAASE,EAAkC,EAAuD,CAChG,MAAO,CACL,GAAGL,EACH,iBAAkBD,EAAWC,EAAK,kBAAkB,EACpD,iBAAkBD,EAAWC,EAAK,kBAAkB,EACpD,WAAYA,EAAIG,YAAiB,EACnC,CACF,CAEA,MAAaG,EAET,CACF,aAAcJ,EACd,gBAAiBE,EACjB,oBAAqBC,CACvB,EAOA,SAAgBE,EACd,EACA,EAC+D,CAC/D,IAAMC,EAAYF,EAAwBG,GACpCC,EAAeF,EAAYA,EAAUR,CAAG,EAAIA,EAElD,MAAO,CAAE,eAAc,MADTrB,EAAoB8B,EAAYC,CACnB,CAAE,CAC/B"}
@@ -1 +1 @@
1
- {"version":3,"file":"failure_view.js","names":["isRecord","value","toFailureView","code","params","status","GALA_ERROR_PHASES","known","phase","uniqueKey","write","FAILURE_OUTCOMES","outcome","retryable","shadow","notFound","isWriteView","view","stringParamOf","name","numberParamOf"],"sources":["../../../src/utils/failure_view.ts"],"sourcesContent":["import { GALA_ERROR_PHASES, type GalaErrorPhase } from '../classes/error_phases.js';\nimport { FAILURE_OUTCOMES, type FailureOutcome } from './failure_outcomes.js';\n\n/**\n * A failure as a PLAIN OBJECT: the facts the SDKs' guards and classifiers (gswap-sdk's\n * `classifyFailure`) read, and nothing else. A real `GalaSDKError` is one (every field below is on\n * it, and on every product subclass); so is the wrapper an app makes from an SDK error to carry\n * through its own layers (frontend_v2's `V2Failure`, the wallet's `WalletSwapError` data), which\n * has a `code` and `params` but is not an `instanceof` anything the SDK owns. gswap-sdk's\n * `classifyFailure`, `isRelayableRefusal`, `isUnprovenAcknowledgement`, `isUninterpretedAnswer`,\n * `isPreSendError`, `isShadowError`, `isNoMarket` and `mayHaveBeenQueued` all accept such an\n * object wherever they accept an SDK error, and decide from the SAME fields in the same way, so an\n * app never has to keep the original error just to ask.\n *\n * Only `code` is required. A field that is missing, or has the wrong type, reads as absent: a view\n * with no `status` is not a 404. Nothing here is text: the SDK never reads `message` of a view.\n *\n * READ OR WRITE: a view is a WRITE's unless it says it is a read. This fails CLOSED on purpose:\n * a 5xx on a write may have been queued (`unknown`, no retry) and the same 5xx on a read changed\n * nothing (`transient`, retry), so a wrapper that drops its `uniqueKey` must never turn the first\n * into the second. A view is a read ONLY when it states `write: false` and has no `uniqueKey`;\n * `GalaSDKError.write` is already set that way for every SDK read. {@link isWriteView}\n * is the one definition.\n *\n * APP ERRORS: a code the SDK catalog does not define is `unknown` (the SDK cannot say what\n * happened, and a wrong \"failed\" invites a duplicate), unless the view declares `outcome`.\n */\nexport interface FailureView {\n /** The catalog code (`'HTTP_ERROR'`, `'CHAIN_REJECTED'`, ...). A string the SDK does not know classifies as `unknown`. */\n readonly code: string;\n /** The error's flat params (`status` of an `HTTP_ERROR`, `reason` of a `SIGNING_FAILED`, ...). */\n readonly params?: Readonly<Record<string, unknown>> | undefined;\n /** The HTTP status of the answer the failure was made from. */\n readonly status?: number | undefined;\n /** How far the request got; when absent, the catalog's phase for `code`. */\n readonly phase?: GalaErrorPhase | undefined;\n /** The `uniqueKey` of the WRITE this is about; its presence makes the failure a write's. */\n readonly uniqueKey?: string | undefined;\n /**\n * `false` says the failed call was a READ (no `uniqueKey` to confirm, nothing pending). Anything\n * else, including absent, is a write: see the note on {@link FailureView}. With a `uniqueKey`\n * the failure is a write whatever this says.\n */\n readonly write?: boolean | undefined;\n /**\n * What an error the APP raised means, for a `code` the SDK catalog does not define (`'POSITION_STALE'`,\n * `'AMOUNT_SIDE'`): `not_sent` for a step that failed before anything was signed or sent, and so\n * on. The SDK honours it ONLY for such a code: for a catalog code the SDK's own table decides, so\n * an app cannot declare a refusal the SDK knows to be unknown as safe. A non-catalog code with no\n * `outcome` stays `unknown`, and `mayHaveBeenQueued` is then `true`.\n */\n readonly outcome?: FailureOutcome | undefined;\n /**\n * WITHHOLD-ONLY: `false` takes Retry away from the declared `outcome` (an app's `DID_NOT_QUEUE`\n * is `{ outcome: 'not_queued', retryable: false }`, the SDK's `NOT_QUEUED_FINAL`). Any other\n * value, `true` included, reads as absent: a view can never GRANT Retry to an outcome that does\n * not have it, and it is read only together with `outcome`, for a code the catalog does not\n * define.\n */\n readonly retryable?: false | undefined;\n /** True when the failure came from the shadow (dark) path. */\n readonly shadow?: boolean | undefined;\n /** True for \"that thing does not exist\" (`GalaSDKError.notFound`: a market, for gswap-sdk). */\n readonly notFound?: boolean | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Reads the failure view of any value: a `GalaSDKError`, or a plain object with a string `code`\n * (and, optionally, `params`, `status`, `phase`, `uniqueKey`, `shadow`, `notFound`). Anything else\n * (a string, a wallet error with a numeric `code`, `null`) has no view and is `undefined`.\n *\n * Having a view does not mean the SDK knows the code: an ethers error is `{ code:\n * 'ACTION_REJECTED' }` and has a view too. The SDK's guards compare the code with the catalog.\n *\n * @example\n * ```ts\n * const view = toFailureView(error); // an SDK error, or an app's `{ code, params, status }` wrapper\n * if (view?.code === 'CHAIN_REJECTED') showChainRejection(view.params);\n * ```\n */\nexport function toFailureView(value: unknown): FailureView | undefined {\n if (!isRecord(value)) return undefined;\n const { code, params, status, phase, uniqueKey, write, outcome, retryable, shadow, notFound } =\n value;\n if (typeof code !== 'string' || code === '') return undefined;\n return {\n code,\n params: isRecord(params) && !Array.isArray(params) ? params : undefined,\n status: typeof status === 'number' && Number.isFinite(status) ? status : undefined,\n phase: GALA_ERROR_PHASES.find((known) => known === phase),\n uniqueKey: typeof uniqueKey === 'string' && uniqueKey !== '' ? uniqueKey : undefined,\n write: typeof write === 'boolean' ? write : undefined,\n outcome: FAILURE_OUTCOMES.find((known) => known === outcome),\n retryable: retryable === false ? false : undefined,\n shadow: typeof shadow === 'boolean' ? shadow : undefined,\n notFound: typeof notFound === 'boolean' ? notFound : undefined,\n };\n}\n\n/**\n * True when a failure is a WRITE's: it names a `uniqueKey`, or it does not say `write: false`.\n * Fail-closed (see {@link FailureView}): only an explicit read is a read.\n */\nexport function isWriteView(view: FailureView): boolean {\n return view.uniqueKey !== undefined || view.write !== false;\n}\n\n/** A param of a view, when it is a string. */\nexport function stringParamOf(view: FailureView, name: string): string | undefined {\n const value = view.params?.[name];\n return typeof value === 'string' ? value : undefined;\n}\n\n/** A param of a view, when it is a finite number. */\nexport function numberParamOf(view: FailureView, name: string): number | undefined {\n const value = view.params?.[name];\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n"],"mappings":"wHAkEA,SAASA,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAgBA,SAAgBC,EAAc,EAAyC,CACrE,GAAI,CAACF,EAASC,CAAK,EAAG,OACtB,GAAM,CAAE,OAAM,SAAQ,SAAQ,QAAO,YAAW,QAAO,UAAS,YAAW,SAAQ,YACjFA,EACF,GAAI,OAAOE,GAAS,UAAYA,IAAS,GACzC,MAAO,CACL,OACA,OAAQH,EAASI,CAAM,GAAK,CAAC,MAAM,QAAQA,CAAM,EAAIA,EAAS,IAAA,GAC9D,OAAQ,OAAOC,GAAW,UAAY,OAAO,SAASA,CAAM,EAAIA,EAAS,IAAA,GACzE,MAAOC,EAAkB,KAAM,GAAUC,IAAUC,CAAK,EACxD,UAAW,OAAOC,GAAc,UAAYA,IAAc,GAAKA,EAAY,IAAA,GAC3E,MAAO,OAAOC,GAAU,UAAYA,EAAQ,IAAA,GAC5C,QAASC,EAAiB,KAAM,GAAUJ,IAAUK,CAAO,EAC3D,UAAWC,IAAc,IAAgB,IAAA,GACzC,OAAQ,OAAOC,GAAW,UAAYA,EAAS,IAAA,GAC/C,SAAU,OAAOC,GAAa,UAAYA,EAAW,IAAA,EACvD,CACF,CAMA,SAAgBC,EAAY,EAA4B,CACtD,OAAOC,EAAK,YAAc,IAAA,IAAaA,EAAK,QAAU,EACxD,CAGA,SAAgBC,EAAc,EAAmB,EAAkC,CACjF,IAAMjB,EAAQgB,EAAK,SAASE,GAC5B,OAAO,OAAOlB,GAAU,SAAWA,EAAQ,IAAA,EAC7C,CAGA,SAAgBmB,EAAc,EAAmB,EAAkC,CACjF,IAAMnB,EAAQgB,EAAK,SAASE,GAC5B,OAAO,OAAOlB,GAAU,UAAY,OAAO,SAASA,CAAK,EAAIA,EAAQ,IAAA,EACvE"}
1
+ {"version":3,"file":"failure_view.js","names":["isRecord","value","toFailureView","code","params","status","GALA_ERROR_PHASES","known","phase","uniqueKey","write","FAILURE_OUTCOMES","outcome","retryable","shadow","notFound","isWriteView","view","stringParamOf","name","numberParamOf"],"sources":["../../../src/utils/failure_view.ts"],"sourcesContent":["import { GALA_ERROR_PHASES, type GalaErrorPhase } from '../classes/error_phases.js';\nimport { FAILURE_OUTCOMES, type FailureOutcome } from './failure_outcomes.js';\n\n/**\n * A failure as a PLAIN OBJECT: the facts the SDKs' guards and classifiers (gswap-sdk's\n * `classifyFailure`) read, and nothing else. A real `GalaSDKError` is one (every field below is on\n * it, and on every product subclass); so is the wrapper an app makes from an SDK error to carry\n * through its own layers (an app's own failure class or error data), which\n * has a `code` and `params` but is not an `instanceof` anything the SDK owns. gswap-sdk's\n * `classifyFailure`, `isRelayableRefusal`, `isUnprovenAcknowledgement`, `isUninterpretedAnswer`,\n * `isPreSendError`, `isShadowError`, `isNoMarket` and `mayHaveBeenQueued` all accept such an\n * object wherever they accept an SDK error, and decide from the SAME fields in the same way, so an\n * app never has to keep the original error just to ask.\n *\n * Only `code` is required. A field that is missing, or has the wrong type, reads as absent: a view\n * with no `status` is not a 404. Nothing here is text: the SDK never reads `message` of a view.\n *\n * READ OR WRITE: a view is a WRITE's unless it says it is a read. This fails CLOSED on purpose:\n * a 5xx on a write may have been queued (`unknown`, no retry) and the same 5xx on a read changed\n * nothing (`transient`, retry), so a wrapper that drops its `uniqueKey` must never turn the first\n * into the second. A view is a read ONLY when it states `write: false` and has no `uniqueKey`;\n * `GalaSDKError.write` is already set that way for every SDK read. {@link isWriteView}\n * is the one definition.\n *\n * APP ERRORS: a code the SDK catalog does not define is `unknown` (the SDK cannot say what\n * happened, and a wrong \"failed\" invites a duplicate), unless the view declares `outcome`.\n */\nexport interface FailureView {\n /** The catalog code (`'HTTP_ERROR'`, `'CHAIN_REJECTED'`, ...). A string the SDK does not know classifies as `unknown`. */\n readonly code: string;\n /** The error's flat params (`status` of an `HTTP_ERROR`, `reason` of a `SIGNING_FAILED`, ...). */\n readonly params?: Readonly<Record<string, unknown>> | undefined;\n /** The HTTP status of the answer the failure was made from. */\n readonly status?: number | undefined;\n /** How far the request got; when absent, the catalog's phase for `code`. */\n readonly phase?: GalaErrorPhase | undefined;\n /** The `uniqueKey` of the WRITE this is about; its presence makes the failure a write's. */\n readonly uniqueKey?: string | undefined;\n /**\n * `false` says the failed call was a READ (no `uniqueKey` to confirm, nothing pending). Anything\n * else, including absent, is a write: see the note on {@link FailureView}. With a `uniqueKey`\n * the failure is a write whatever this says.\n */\n readonly write?: boolean | undefined;\n /**\n * What an error the APP raised means, for a `code` the SDK catalog does not define (`'POSITION_STALE'`,\n * `'AMOUNT_SIDE'`): `not_sent` for a step that failed before anything was signed or sent, and so\n * on. The SDK honours it ONLY for such a code: for a catalog code the SDK's own table decides, so\n * an app cannot declare a refusal the SDK knows to be unknown as safe. A non-catalog code with no\n * `outcome` stays `unknown`, and `mayHaveBeenQueued` is then `true`.\n */\n readonly outcome?: FailureOutcome | undefined;\n /**\n * WITHHOLD-ONLY: `false` takes Retry away from the declared `outcome` (an app's `DID_NOT_QUEUE`\n * is `{ outcome: 'not_queued', retryable: false }`, the SDK's `NOT_QUEUED_FINAL`). Any other\n * value, `true` included, reads as absent: a view can never GRANT Retry to an outcome that does\n * not have it, and it is read only together with `outcome`, for a code the catalog does not\n * define.\n */\n readonly retryable?: false | undefined;\n /** True when the failure came from the shadow (dark) path. */\n readonly shadow?: boolean | undefined;\n /** True for \"that thing does not exist\" (`GalaSDKError.notFound`: a market, for gswap-sdk). */\n readonly notFound?: boolean | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Reads the failure view of any value: a `GalaSDKError`, or a plain object with a string `code`\n * (and, optionally, `params`, `status`, `phase`, `uniqueKey`, `shadow`, `notFound`). Anything else\n * (a string, a wallet error with a numeric `code`, `null`) has no view and is `undefined`.\n *\n * Having a view does not mean the SDK knows the code: an ethers error is `{ code:\n * 'ACTION_REJECTED' }` and has a view too. The SDK's guards compare the code with the catalog.\n *\n * @example\n * ```ts\n * const view = toFailureView(error); // an SDK error, or an app's `{ code, params, status }` wrapper\n * if (view?.code === 'CHAIN_REJECTED') showChainRejection(view.params);\n * ```\n */\nexport function toFailureView(value: unknown): FailureView | undefined {\n if (!isRecord(value)) return undefined;\n const { code, params, status, phase, uniqueKey, write, outcome, retryable, shadow, notFound } =\n value;\n if (typeof code !== 'string' || code === '') return undefined;\n return {\n code,\n params: isRecord(params) && !Array.isArray(params) ? params : undefined,\n status: typeof status === 'number' && Number.isFinite(status) ? status : undefined,\n phase: GALA_ERROR_PHASES.find((known) => known === phase),\n uniqueKey: typeof uniqueKey === 'string' && uniqueKey !== '' ? uniqueKey : undefined,\n write: typeof write === 'boolean' ? write : undefined,\n outcome: FAILURE_OUTCOMES.find((known) => known === outcome),\n retryable: retryable === false ? false : undefined,\n shadow: typeof shadow === 'boolean' ? shadow : undefined,\n notFound: typeof notFound === 'boolean' ? notFound : undefined,\n };\n}\n\n/**\n * True when a failure is a WRITE's: it names a `uniqueKey`, or it does not say `write: false`.\n * Fail-closed (see {@link FailureView}): only an explicit read is a read.\n */\nexport function isWriteView(view: FailureView): boolean {\n return view.uniqueKey !== undefined || view.write !== false;\n}\n\n/** A param of a view, when it is a string. */\nexport function stringParamOf(view: FailureView, name: string): string | undefined {\n const value = view.params?.[name];\n return typeof value === 'string' ? value : undefined;\n}\n\n/** A param of a view, when it is a finite number. */\nexport function numberParamOf(view: FailureView, name: string): number | undefined {\n const value = view.params?.[name];\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n"],"mappings":"wHAkEA,SAASA,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAgBA,SAAgBC,EAAc,EAAyC,CACrE,GAAI,CAACF,EAASC,CAAK,EAAG,OACtB,GAAM,CAAE,OAAM,SAAQ,SAAQ,QAAO,YAAW,QAAO,UAAS,YAAW,SAAQ,YACjFA,EACF,GAAI,OAAOE,GAAS,UAAYA,IAAS,GACzC,MAAO,CACL,OACA,OAAQH,EAASI,CAAM,GAAK,CAAC,MAAM,QAAQA,CAAM,EAAIA,EAAS,IAAA,GAC9D,OAAQ,OAAOC,GAAW,UAAY,OAAO,SAASA,CAAM,EAAIA,EAAS,IAAA,GACzE,MAAOC,EAAkB,KAAM,GAAUC,IAAUC,CAAK,EACxD,UAAW,OAAOC,GAAc,UAAYA,IAAc,GAAKA,EAAY,IAAA,GAC3E,MAAO,OAAOC,GAAU,UAAYA,EAAQ,IAAA,GAC5C,QAASC,EAAiB,KAAM,GAAUJ,IAAUK,CAAO,EAC3D,UAAWC,IAAc,IAAgB,IAAA,GACzC,OAAQ,OAAOC,GAAW,UAAYA,EAAS,IAAA,GAC/C,SAAU,OAAOC,GAAa,UAAYA,EAAW,IAAA,EACvD,CACF,CAMA,SAAgBC,EAAY,EAA4B,CACtD,OAAOC,EAAK,YAAc,IAAA,IAAaA,EAAK,QAAU,EACxD,CAGA,SAAgBC,EAAc,EAAmB,EAAkC,CACjF,IAAMjB,EAAQgB,EAAK,SAASE,GAC5B,OAAO,OAAOlB,GAAU,SAAWA,EAAQ,IAAA,EAC7C,CAGA,SAAgBmB,EAAc,EAAmB,EAAkC,CACjF,IAAMnB,EAAQgB,EAAK,SAASE,GAC5B,OAAO,OAAOlB,GAAU,UAAY,OAAO,SAASA,CAAK,EAAIA,EAAQ,IAAA,EACvE"}
@@ -1 +1 @@
1
- {"version":3,"file":"signing.js","names":["textEncoder","toDeterministicNode","node","candidate","deterministicNode","rawNode","item","record","members","key","value","serialize","result","getPayloadToSign","rest","dto","\"signature\"","\"multisig\"","\"trace\"","prefix","ETHEREUM_SIGNED_MESSAGE","calculatePersonalSignPrefix","message","personalSignPrefixFor","withoutPrefix","\"prefix\"","fixpointPrefixFor","payloadLength","previousLength","invalidPrivateKey","GalaSDKError","decodeBase64","input","unpadded","bytes","buffer","bits","char","decodeHex","index","normalizePrivateKey","secp256k1","signHash","hash","signature","privateKey","bytesToHex","ethAddressOfPrivateKey","publicKey","keccak_256","keccak256Utf8","data","signSerializedNative","serializedDto","signNative","signPersonalMessage"],"sources":["../../../src/utils/signing.ts"],"sourcesContent":["/**\n * SDK-owned signing primitives.\n *\n * Everything the SDK needs to produce a GalaChain signature lives here, with no dependency on\n * `@gala-chain/api` (which drags `secp256k1` native bindings, `reflect-metadata`, `class-validator`\n * and its own `bignumber.js` major into every consumer). The only runtime dependencies are the\n * audited, pure-JS `@noble/curves` (secp256k1) and `@noble/hashes` (keccak256), which run\n * unchanged in browsers, MV3 service workers, Node and React Native/Hermes.\n *\n * Every function here is pinned byte-for-byte to the signatures produced by `@gala-chain/api`\n * (`serialize`, `signatures.getSignature`), `@gala-chain/connect`, the Gala Wallet extension and\n * frontend_v2 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 frontend_v2 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 defi-backend recomputes, so it only exists to keep the submitted\n * body byte-identical to what frontend_v2 has always sent.\n */\nexport function fixpointPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n let payloadLength = textEncoder.encode(getPayloadToSign(withoutPrefix)).length;\n let prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n let previousLength = -1;\n while (payloadLength !== previousLength) {\n previousLength = payloadLength;\n prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n payloadLength = textEncoder.encode(getPayloadToSign({ ...withoutPrefix, prefix })).length;\n }\n return prefix;\n}\n\nfunction invalidPrivateKey(reason: InvalidPrivateKeyReason): GalaSDKError<'INVALID_PRIVATE_KEY'> {\n return new GalaSDKError('INVALID_PRIVATE_KEY', { reason });\n}\n\nconst BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nfunction decodeBase64(input: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(input) || input.length % 4 !== 0) return undefined;\n const unpadded = input.replace(/=+$/u, '');\n const bytes: number[] = [];\n let buffer = 0;\n let bits = 0;\n for (const char of unpadded) {\n buffer = (buffer << 6) | BASE64_ALPHABET.indexOf(char);\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((buffer >> bits) & 0xff);\n }\n }\n return Uint8Array.from(bytes);\n}\n\nfunction decodeHex(input: string): Uint8Array {\n const bytes = new Uint8Array(input.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = parseInt(input.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Normalizes a secp256k1 private key to a fresh 32-byte array (the caller may zero it). Also\n * accepts 32 raw bytes, which are validated and copied. For strings it accepts what `@gala-chain/api`'s\n * `normalizePrivateKey` accepted for a usable key: 64 hex characters (optionally `0x`-prefixed;\n * a 63-character hex key is left-padded with a zero) or a 44-character base64 string.\n *\n * @throws GalaSDKError (`INVALID_PRIVATE_KEY`; `params.reason` is one of\n * `INVALID_PRIVATE_KEY_REASONS`: `wrong_length` for raw bytes that are not 32 long,\n * `bad_encoding` for any other string shape, `not_on_curve` for an out-of-range scalar).\n */\nexport function normalizePrivateKey(input: string | Uint8Array): Uint8Array {\n if (typeof input !== 'string') {\n // Raw bytes: validated, then COPIED, so zeroing the result never touches the caller's array.\n if (!(input instanceof Uint8Array) || input.length !== 32) {\n throw invalidPrivateKey('wrong_length');\n }\n if (!secp256k1.utils.isValidSecretKey(input)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return Uint8Array.from(input);\n }\n const withoutPrefix = input.startsWith('0x') ? input.slice(2) : input;\n let key: Uint8Array | undefined;\n if (/^[0-9a-fA-F]{63,64}$/u.test(withoutPrefix)) {\n key = decodeHex(withoutPrefix.length === 63 ? `0${withoutPrefix}` : withoutPrefix);\n } else if (withoutPrefix.length === 44) {\n key = decodeBase64(withoutPrefix);\n }\n if (key?.length !== 32) {\n throw invalidPrivateKey('bad_encoding');\n }\n if (!secp256k1.utils.isValidSecretKey(key)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return key;\n}\n\n/**\n * Signs a 32-byte keccak256 hash and returns GalaChain's recoverable signature: 64 hex `r` +\n * 64 hex `s` + `1b`/`1c` (`v`), lowercase, no `0x`. Deterministic (RFC 6979) and low-S, exactly\n * what `@gala-chain/api` and the Gala Wallet produce. A DER signature carries no recovery byte\n * and cannot be used: the chain RECOVERS the signer from the signature.\n */\nexport function signHash(privateKey: Uint8Array, hash: Uint8Array): string {\n if (hash.length !== 32) {\n throw new GalaSDKError('INVALID_SIGNING_HASH_LENGTH', { length: hash.length });\n }\n const signature = secp256k1.sign(hash, privateKey, { prehash: false, lowS: true });\n // compact raw bytes are r (32) || s (32); the recovery id becomes v.\n return bytesToHex(signature.toBytes('compact')) + (signature.recovery === 1 ? '1c' : '1b');\n}\n\n/**\n * The lowercase `0x` Ethereum address (last 20 bytes of keccak256 of the uncompressed public key)\n * of a normalized private key. The Gala `eth|` identity of a key is this address.\n */\nexport function ethAddressOfPrivateKey(privateKey: Uint8Array): string {\n const publicKey = secp256k1.getPublicKey(privateKey, false);\n return `0x${bytesToHex(keccak_256(publicKey.slice(1)).slice(-20))}`;\n}\n\n/** keccak256 of a string's UTF-8 bytes. */\nexport function keccak256Utf8(data: string): Uint8Array {\n return keccak_256(textEncoder.encode(data));\n}\n\n/**\n * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes, with no\n * prefix and no signature envelope. The caller owns serialization, so the bytes shown to a user\n * and the bytes signed can never diverge.\n */\nexport function signSerializedNative(privateKey: Uint8Array, serializedDto: string): string {\n return signHash(privateKey, keccak256Utf8(serializedDto));\n}\n\n/**\n * GalaChain NATIVE signature for a DTO: keccak256 of `getPayloadToSign(dto)`, signed with\n * secp256k1. Byte-identical to `signatures.getSignature` from `@gala-chain/api`.\n */\nexport function signNative(privateKey: Uint8Array, dto: Record<string, unknown>): string {\n return signSerializedNative(privateKey, getPayloadToSign(dto));\n}\n\n/**\n * Personal-sign hash and signature: keccak256(`prefix` + `message`), both hashed VERBATIM with no\n * further EIP-191 wrapping. Passing `prefix = calculatePersonalSignPrefix(message)` reproduces a\n * wallet's `personal_sign` of `message`. Gala Wallet's `gala_signChainDto` (personal-sign\n * scheme) hashes `prefix` + the exact string it is handed, which can differ from the bare message\n * (see the `signatureOverPrefixlessBody` vectors); that quirk is why the two inputs stay separate.\n */\nexport function signPersonalMessage(\n privateKey: Uint8Array,\n prefix: string,\n message: string,\n): string {\n return signHash(privateKey, keccak256Utf8(prefix + message));\n}\n"],"mappings":"iNAmBA,MAAMA,EAAc,IAAI,YAExB,SAASC,EAAoB,EAAwB,CACnD,GAAIC,GAAS,KAA4B,OAAOA,EAChD,GAAIA,aAAgB,OAAQ,OAAOA,EAAK,SAAS,EACjD,IAAMC,EAAYD,EAClB,OAAO,OAAOC,EAAU,QAAW,WAC9B,QAAQ,MAAMA,EAAU,OAAQD,EAAM,CAAC,CAAC,EACzCA,CACN,CAEA,SAASE,EAAkB,EAAsC,CAC/D,IAAMF,EAAOD,EAAoBI,CAAO,EACxC,GAAIH,IAAS,IAAA,GAAW,OACxB,GAAI,OAAOA,GAAS,WAAYA,EAAe,OAAO,KAAK,UAAUA,CAAI,EAEzE,GAAI,MAAM,QAAQA,CAAI,EAEpB,MAAO,IADQA,EAAmB,IAAK,GAASE,EAAkBE,CAAI,GAAK,MAC5D,CAAC,CAAC,KAAK,GAAG,EAAE,GAG7B,IAAMC,EAASL,EACTM,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAO,OAAO,KAAKF,CAAM,CAAC,CAAC,KAAK,EAAG,CAC5C,IAAMG,EAAQN,EAAkBG,EAAOE,EAAI,EACvCC,I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AS,EAAwB,EAA0B,CACzE,GAAIC,EAAK,SAAW,GAClB,MAAM,IAAIb,EAAa,8BAA+B,CAAE,OAAQa,EAAK,MAAO,CAAC,EAE/E,IAAMC,EAAYH,EAAU,KAAKE,EAAME,EAAY,CAAE,QAAS,GAAO,KAAM,EAAK,CAAC,EAEjF,OAAOC,EAAWF,EAAU,QAAQ,SAAS,CAAC,GAAKA,EAAU,WAAa,EAAI,KAAO,KACvF,CAMA,SAAgBG,EAAuB,EAAgC,CACrE,IAAMC,EAAYP,EAAU,aAAaI,EAAY,EAAK,EAC1D,MAAO,KAAKC,EAAWG,EAAWD,EAAU,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,GAClE,CAGA,SAAgBE,EAAc,EAA0B,CACtD,OAAOD,EAAWjD,EAAY,OAAOmD,CAAI,CAAC,CAC5C,CAOA,SAAgBC,EAAqB,EAAwB,EAA+B,CAC1F,OAAOV,EAASG,EAAYK,EAAcG,CAAa,CAAC,CAC1D,CAMA,SAAgBC,EAAW,EAAwB,EAAsC,CACvF,OAAOF,EAAqBP,EAAYhC,EAAiBE,CAAG,CAAC,CAC/D,CASA,SAAgBwC,EACd,EACA,EACA,EACQ,CACR,OAAOb,EAASG,EAAYK,EAAc/B,EAASG,CAAO,CAAC,CAC7D"}
1
+ {"version":3,"file":"signing.js","names":["textEncoder","toDeterministicNode","node","candidate","deterministicNode","rawNode","item","record","members","key","value","serialize","result","getPayloadToSign","rest","dto","\"signature\"","\"multisig\"","\"trace\"","prefix","ETHEREUM_SIGNED_MESSAGE","calculatePersonalSignPrefix","message","personalSignPrefixFor","withoutPrefix","\"prefix\"","fixpointPrefixFor","payloadLength","previousLength","invalidPrivateKey","GalaSDKError","decodeBase64","input","unpadded","bytes","buffer","bits","char","decodeHex","index","normalizePrivateKey","secp256k1","signHash","hash","signature","privateKey","bytesToHex","ethAddressOfPrivateKey","publicKey","keccak_256","keccak256Utf8","data","signSerializedNative","serializedDto","signNative","signPersonalMessage"],"sources":["../../../src/utils/signing.ts"],"sourcesContent":["/**\n * SDK-owned signing primitives.\n *\n * Everything the SDK needs to produce a GalaChain signature lives here, with no dependency on\n * `@gala-chain/api` (which drags `secp256k1` native bindings, `reflect-metadata`, `class-validator`\n * and its own `bignumber.js` major into every consumer). The only runtime dependencies are the\n * audited, pure-JS `@noble/curves` (secp256k1) and `@noble/hashes` (keccak256), which run\n * unchanged in browsers, MV3 service workers, Node and React Native/Hermes.\n *\n * Every function here is pinned byte-for-byte to the signatures produced by `@gala-chain/api`\n * (`serialize`, `signatures.getSignature`), `@gala-chain/connect`, the Gala Wallet extension and\n * the gSwap web app by the golden-vector suite in `tests/signing-golden.test.ts`.\n */\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { bytesToHex } from '@noble/hashes/utils';\nimport type { InvalidPrivateKeyReason } from '../classes/error_catalog.js';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\n\nconst textEncoder = new TextEncoder();\n\nfunction toDeterministicNode(node: unknown): unknown {\n if (node === null || node === undefined) return node;\n if (node instanceof RegExp) return node.toString();\n const candidate = node as { toJSON?: unknown };\n return typeof candidate.toJSON === 'function'\n ? (Reflect.apply(candidate.toJSON, node, []) as unknown)\n : node;\n}\n\nfunction deterministicNode(rawNode: unknown): string | undefined {\n const node = toDeterministicNode(rawNode);\n if (node === undefined) return undefined;\n if (typeof node !== 'object' || node === null) return JSON.stringify(node);\n\n if (Array.isArray(node)) {\n const items = (node as unknown[]).map((item) => deterministicNode(item) ?? 'null');\n return `[${items.join(',')}]`;\n }\n\n const record = node as Record<string, unknown>;\n const members: string[] = [];\n for (const key of Object.keys(record).sort()) {\n const value = deterministicNode(record[key]);\n if (value === undefined) continue;\n members.push(`${JSON.stringify(key)}:${value}`);\n }\n return `{${members.join(',')}}`;\n}\n\n/**\n * GalaChain's deterministic JSON: object keys sorted (UTF-16 code-unit order) at every depth, no\n * whitespace, `undefined`/function members dropped, `toJSON()` honored. Byte-identical to\n * `serialize` from `@gala-chain/api` / `json-stringify-deterministic` for every JSON-shaped\n * value, which is all a DTO ever is.\n *\n * @throws TypeError for circular structures and BigInt values (as `JSON.stringify` does) and\n * when the value itself has no JSON representation (`undefined`, a function, a symbol).\n */\nexport function serialize(value: unknown): string {\n // Same cycle/BigInt guard json-stringify-deterministic runs before walking the value.\n JSON.stringify(value);\n const result = deterministicNode(value);\n if (result === undefined) {\n throw new TypeError('Cannot serialize a value with no JSON representation.');\n }\n return result;\n}\n\n/**\n * The exact string GalaChain hashes for a DTO: the (optional, string) `prefix` field PREPENDED to\n * the deterministic serialization of the DTO WITHOUT `signature`, `multisig`, `trace` and `prefix`.\n * Equivalent to `@gala-chain/api` 3.x `getPayloadToSign` for every non-EIP-712 DTO.\n */\nexport function getPayloadToSign(dto: Record<string, unknown>): string {\n const { prefix, ...rest } = dto;\n delete rest['signature'];\n delete rest['multisig'];\n delete rest['trace'];\n const head = typeof prefix === 'string' ? prefix : '';\n return head + serialize(rest);\n}\n\n// Built via String.fromCharCode rather than a literal escape ON PURPOSE: a literal control byte in\n// source is invisible and fragile under editors/diffs/copy-paste; this keeps the source ordinary.\nconst ETHEREUM_SIGNED_MESSAGE = String.fromCharCode(0x19) + 'Ethereum Signed Message:\\n';\n\n/**\n * The EIP-191 header for `message`: `\"\\x19Ethereum Signed Message:\\n\"` + the message's UTF-8 BYTE\n * length. This is what a wallet's `personal_sign` prepends, and what the chain recomputes when it\n * recovers a personal-signed DTO.\n */\nexport function calculatePersonalSignPrefix(message: string): string {\n return ETHEREUM_SIGNED_MESSAGE + String(textEncoder.encode(message).length);\n}\n\n/**\n * The EIP-191 header for `serialize(dto)` (any `prefix` already on the DTO is ignored). This is\n * deliberately the same string the signers hand a wallet to sign, so the header's length can never\n * disagree with the signed message. Wallet-neutral: it is the value both a browser wallet's\n * `personal_sign` and Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepend.\n */\nexport function personalSignPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n return calculatePersonalSignPrefix(serialize(withoutPrefix));\n}\n\n/**\n * The `@gala-chain/connect`-style prefix the gSwap web app puts in the body of an EIP-712 write: the\n * EIP-191 header whose number counts the prefix string ITSELF plus the body (the UTF-8 length of\n * `getPayloadToSign({ ...dto, prefix })`), found by fixpoint because adding the prefix changes the\n * length (a body of 99 bytes settles on 101).\n *\n * It is NOT a personal-sign prefix (a personal-sign write with this value recovers a phantom\n * signer; use `personalSignPrefixFor`). Under EIP-712 the field is an untyped extra that the\n * typed-data hash ignores and the backend recomputes, so it only exists to keep the submitted\n * body byte-identical to what the gSwap web app has always sent.\n */\nexport function fixpointPrefixFor(dto: Record<string, unknown>): string {\n const withoutPrefix: Record<string, unknown> = { ...dto };\n delete withoutPrefix['prefix'];\n let payloadLength = textEncoder.encode(getPayloadToSign(withoutPrefix)).length;\n let prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n let previousLength = -1;\n while (payloadLength !== previousLength) {\n previousLength = payloadLength;\n prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);\n payloadLength = textEncoder.encode(getPayloadToSign({ ...withoutPrefix, prefix })).length;\n }\n return prefix;\n}\n\nfunction invalidPrivateKey(reason: InvalidPrivateKeyReason): GalaSDKError<'INVALID_PRIVATE_KEY'> {\n return new GalaSDKError('INVALID_PRIVATE_KEY', { reason });\n}\n\nconst BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nfunction decodeBase64(input: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(input) || input.length % 4 !== 0) return undefined;\n const unpadded = input.replace(/=+$/u, '');\n const bytes: number[] = [];\n let buffer = 0;\n let bits = 0;\n for (const char of unpadded) {\n buffer = (buffer << 6) | BASE64_ALPHABET.indexOf(char);\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((buffer >> bits) & 0xff);\n }\n }\n return Uint8Array.from(bytes);\n}\n\nfunction decodeHex(input: string): Uint8Array {\n const bytes = new Uint8Array(input.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = parseInt(input.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Normalizes a secp256k1 private key to a fresh 32-byte array (the caller may zero it). Also\n * accepts 32 raw bytes, which are validated and copied. For strings it accepts what `@gala-chain/api`'s\n * `normalizePrivateKey` accepted for a usable key: 64 hex characters (optionally `0x`-prefixed;\n * a 63-character hex key is left-padded with a zero) or a 44-character base64 string.\n *\n * @throws GalaSDKError (`INVALID_PRIVATE_KEY`; `params.reason` is one of\n * `INVALID_PRIVATE_KEY_REASONS`: `wrong_length` for raw bytes that are not 32 long,\n * `bad_encoding` for any other string shape, `not_on_curve` for an out-of-range scalar).\n */\nexport function normalizePrivateKey(input: string | Uint8Array): Uint8Array {\n if (typeof input !== 'string') {\n // Raw bytes: validated, then COPIED, so zeroing the result never touches the caller's array.\n if (!(input instanceof Uint8Array) || input.length !== 32) {\n throw invalidPrivateKey('wrong_length');\n }\n if (!secp256k1.utils.isValidSecretKey(input)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return Uint8Array.from(input);\n }\n const withoutPrefix = input.startsWith('0x') ? input.slice(2) : input;\n let key: Uint8Array | undefined;\n if (/^[0-9a-fA-F]{63,64}$/u.test(withoutPrefix)) {\n key = decodeHex(withoutPrefix.length === 63 ? `0${withoutPrefix}` : withoutPrefix);\n } else if (withoutPrefix.length === 44) {\n key = decodeBase64(withoutPrefix);\n }\n if (key?.length !== 32) {\n throw invalidPrivateKey('bad_encoding');\n }\n if (!secp256k1.utils.isValidSecretKey(key)) {\n throw invalidPrivateKey('not_on_curve');\n }\n return key;\n}\n\n/**\n * Signs a 32-byte keccak256 hash and returns GalaChain's recoverable signature: 64 hex `r` +\n * 64 hex `s` + `1b`/`1c` (`v`), lowercase, no `0x`. Deterministic (RFC 6979) and low-S, exactly\n * what `@gala-chain/api` and the Gala Wallet produce. A DER signature carries no recovery byte\n * and cannot be used: the chain RECOVERS the signer from the signature.\n */\nexport function signHash(privateKey: Uint8Array, hash: Uint8Array): string {\n if (hash.length !== 32) {\n throw new GalaSDKError('INVALID_SIGNING_HASH_LENGTH', { length: hash.length });\n }\n const signature = secp256k1.sign(hash, privateKey, { prehash: false, lowS: true });\n // compact raw bytes are r (32) || s (32); the recovery id becomes v.\n return bytesToHex(signature.toBytes('compact')) + (signature.recovery === 1 ? '1c' : '1b');\n}\n\n/**\n * The lowercase `0x` Ethereum address (last 20 bytes of keccak256 of the uncompressed public key)\n * of a normalized private key. The Gala `eth|` identity of a key is this address.\n */\nexport function ethAddressOfPrivateKey(privateKey: Uint8Array): string {\n const publicKey = secp256k1.getPublicKey(privateKey, false);\n return `0x${bytesToHex(keccak_256(publicKey.slice(1)).slice(-20))}`;\n}\n\n/** keccak256 of a string's UTF-8 bytes. */\nexport function keccak256Utf8(data: string): Uint8Array {\n return keccak_256(textEncoder.encode(data));\n}\n\n/**\n * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes, with no\n * prefix and no signature envelope. The caller owns serialization, so the bytes shown to a user\n * and the bytes signed can never diverge.\n */\nexport function signSerializedNative(privateKey: Uint8Array, serializedDto: string): string {\n return signHash(privateKey, keccak256Utf8(serializedDto));\n}\n\n/**\n * GalaChain NATIVE signature for a DTO: keccak256 of `getPayloadToSign(dto)`, signed with\n * secp256k1. Byte-identical to `signatures.getSignature` from `@gala-chain/api`.\n */\nexport function signNative(privateKey: Uint8Array, dto: Record<string, unknown>): string {\n return signSerializedNative(privateKey, getPayloadToSign(dto));\n}\n\n/**\n * Personal-sign hash and signature: keccak256(`prefix` + `message`), both hashed VERBATIM with no\n * further EIP-191 wrapping. Passing `prefix = calculatePersonalSignPrefix(message)` reproduces a\n * wallet's `personal_sign` of `message`. Gala Wallet's `gala_signChainDto` (personal-sign\n * scheme) hashes `prefix` + the exact string it is handed, which can differ from the bare message\n * (see the `signatureOverPrefixlessBody` vectors); that quirk is why the two inputs stay separate.\n */\nexport function signPersonalMessage(\n privateKey: Uint8Array,\n prefix: string,\n message: string,\n): string {\n return signHash(privateKey, keccak256Utf8(prefix + message));\n}\n"],"mappings":"iNAmBA,MAAMA,EAAc,IAAI,YAExB,SAASC,EAAoB,EAAwB,CACnD,GAAIC,GAAS,KAA4B,OAAOA,EAChD,GAAIA,aAAgB,OAAQ,OAAOA,EAAK,SAAS,EACjD,IAAMC,EAAYD,EAClB,OAAO,OAAOC,EAAU,QAAW,WAC9B,QAAQ,MAAMA,EAAU,OAAQD,EAAM,CAAC,CAAC,EACzCA,CACN,CAEA,SAASE,EAAkB,EAAsC,CAC/D,IAAMF,EAAOD,EAAoBI,CAAO,EACxC,GAAIH,IAAS,IAAA,GAAW,OACxB,GAAI,OAAOA,GAAS,WAAYA,EAAe,OAAO,KAAK,UAAUA,CAAI,EAEzE,GAAI,MAAM,QAAQA,CAAI,EAEpB,MAAO,IADQA,EAAmB,IAAK,GAASE,EAAkBE,CAAI,GAAK,MAC5D,CAAC,CAAC,KAAK,GAAG,EAAE,GAG7B,IAAMC,EAASL,EACTM,EAAoB,CAAC,EAC3B,IAAK,IAAMC,KAAO,OAAO,KAAKF,CAAM,CAAC,CAAC,KAAK,EAAG,CAC5C,IAAMG,EAAQN,EAAkBG,EAAOE,EAAI,EACvCC,IAAU,IAAA,IACdF,EAAQ,KAAK,GAAG,KAAK,UAAUC,CAAG,EAAE,GAAGC,GAAO,CAChD,CACA,MAAO,IAAIF,EAAQ,KAAK,GAAG,EAAE,EAC/B,CAWA,SAAgBG,EAAU,EAAwB,CAEhD,KAAK,UAAUD,CAAK,EACpB,IAAME,EAASR,EAAkBM,CAAK,EACtC,GAAIE,IAAW,IAAA,GACb,MAAU,UAAU,uDAAuD,EAE7E,OAAOA,CACT,CAOA,SAAgBC,EAAiB,EAAsC,CACrE,GAAM,CAAE,SAAQ,GAAGC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K,EAC1D,MAAO,KAAKC,EAAWG,EAAWD,EAAU,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,GAClE,CAGA,SAAgBE,EAAc,EAA0B,CACtD,OAAOD,EAAWjD,EAAY,OAAOmD,CAAI,CAAC,CAC5C,CAOA,SAAgBC,EAAqB,EAAwB,EAA+B,CAC1F,OAAOV,EAASG,EAAYK,EAAcG,CAAa,CAAC,CAC1D,CAMA,SAAgBC,EAAW,EAAwB,EAAsC,CACvF,OAAOF,EAAqBP,EAAYhC,EAAiBE,CAAG,CAAC,CAC/D,CASA,SAAgBwC,EACd,EACA,EACA,EACQ,CACR,OAAOb,EAASG,EAAYK,EAAc/B,EAASG,CAAO,CAAC,CAC7D"}
@@ -1,2 +1,2 @@
1
- import{GalaSDKError as e,isGalaError as t,parseJson as n}from"../classes/gala_sdk_error.js";import"../version.js";function r(e,t){if(t===1/0)return()=>void 0;let n=setTimeout(()=>e.abort(),t);return()=>clearTimeout(n)}function i(t,n){if(t===1/0||Number.isFinite(t)&&t>0)return t;throw new e(`INVALID_TIMEOUT`,{field:n,value:t})}const a=/[A-Za-z0-9\-._~!'()*$|:,]/u;function o(e){let t=``;for(let n of e)n===` `?t+=`+`:a.test(n)?t+=n:t+=s(n);return t}function s(e){try{return encodeURIComponent(e)}catch{return`%EF%BF%BD`}}function c(e,t=`standard`){return t===`readable`?Object.entries(e).map(([e,t])=>`${o(e)}=${o(t)}`).join(`&`):new URLSearchParams(e).toString()}function l(e,t={}){let n=/* @__PURE__ */ new Map,r=(e,t=!1)=>{for(let[r,i]of Object.entries(e??{}))t&&n.delete(r.toLowerCase()),n.set(r.toLowerCase(),[r,i])};return e?.userAgent!==!1&&r({"User-Agent":e?.userAgent??`GalaChain-SDK/1.0.0-rc.7`}),r(t.defaults),r(e?.headers),t.json===!0&&!n.has(`content-type`)&&r({"Content-Type":`application/json`}),r(t.fixed,!0),Object.fromEntries(n.values())}const u=async(t,n)=>{try{return await fetch(t,n)}catch(r){throw n?.signal?.aborted===!0?r:new e(`TRANSPORT_ERROR`,{url:t},{url:t,cause:r})}};async function d(n,i,a,o,s){let c=new AbortController,l=r(c,o),u=a.signal,d=()=>c.abort();u?.addEventListener(`abort`,d,{once:!0});let f=s?.write===!1;try{return await n(i,{...a,signal:c.signal})}catch(n){throw u?.aborted===!0?n:c.signal.aborted?new e(`REQUEST_TIMEOUT`,{url:i,timeoutMs:o},{url:i,cause:n,...f?{write:!1}:{}}):f&&t(n,`TRANSPORT_ERROR`)&&n.write?new e(`TRANSPORT_ERROR`,{url:n.url??i},{url:n.url??i,cause:n.cause,write:!1}):n}finally{l(),u?.removeEventListener(`abort`,d)}}async function f(e){let t=await e.text();return n(t)??t}function p(e,t){let n=e.headers;if(n===void 0)return;if(g(n)){let e=n.get(t);return e===null||e===``?void 0:e}let r=Object.entries(n).find(([e])=>e.toLowerCase()===t.toLowerCase())?.[1];return r===void 0||r===``?void 0:r}function m(e){let t=p(e,`retry-after`);if(t===void 0)return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}function h(e,t=`x-block-number`){let n=p(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function g(e){return`get`in e&&typeof e.get==`function`}export{r as armTimeout,c as buildQueryString,l as buildRequestHeaders,u as fetchRequestor,h as readBlockNumberHeader,p as readHeader,f as readResponseBody,m as readRetryAfter,d as requestWithTimeout,i as validateTimeoutMs};
1
+ import{GalaSDKError as e,isGalaError as t,parseJson as n}from"../classes/gala_sdk_error.js";import"../version.js";function r(e,t){if(t===1/0)return()=>void 0;let n=setTimeout(()=>e.abort(),t);return()=>clearTimeout(n)}function i(t,n){if(t===1/0||Number.isFinite(t)&&t>0)return t;throw new e(`INVALID_TIMEOUT`,{field:n,value:t})}const a=/[A-Za-z0-9\-._~!'()*$|:,]/u;function o(e){let t=``;for(let n of e)n===` `?t+=`+`:a.test(n)?t+=n:t+=s(n);return t}function s(e){try{return encodeURIComponent(e)}catch{return`%EF%BF%BD`}}function c(e,t=`standard`){return t===`readable`?Object.entries(e).map(([e,t])=>`${o(e)}=${o(t)}`).join(`&`):new URLSearchParams(e).toString()}function l(e,t={}){let n=/* @__PURE__ */ new Map,r=(e,t=!1)=>{for(let[r,i]of Object.entries(e??{}))t&&n.delete(r.toLowerCase()),n.set(r.toLowerCase(),[r,i])};return e?.userAgent!==!1&&r({"User-Agent":e?.userAgent??`GalaChain-SDK/1.0.0-rc.8`}),r(t.defaults),r(e?.headers),t.json===!0&&!n.has(`content-type`)&&r({"Content-Type":`application/json`}),r(t.fixed,!0),Object.fromEntries(n.values())}const u=async(t,n)=>{try{return await fetch(t,n)}catch(r){throw n?.signal?.aborted===!0?r:new e(`TRANSPORT_ERROR`,{url:t},{url:t,cause:r})}};async function d(n,i,a,o,s){let c=new AbortController,l=r(c,o),u=a.signal,d=()=>c.abort();u?.addEventListener(`abort`,d,{once:!0});let f=s?.write===!1;try{return await n(i,{...a,signal:c.signal})}catch(n){throw u?.aborted===!0?n:c.signal.aborted?new e(`REQUEST_TIMEOUT`,{url:i,timeoutMs:o},{url:i,cause:n,...f?{write:!1}:{}}):f&&t(n,`TRANSPORT_ERROR`)&&n.write?new e(`TRANSPORT_ERROR`,{url:n.url??i},{url:n.url??i,cause:n.cause,write:!1}):n}finally{l(),u?.removeEventListener(`abort`,d)}}async function f(e){let t=await e.text();return n(t)??t}function p(e,t){let n=e.headers;if(n===void 0)return;if(g(n)){let e=n.get(t);return e===null||e===``?void 0:e}let r=Object.entries(n).find(([e])=>e.toLowerCase()===t.toLowerCase())?.[1];return r===void 0||r===``?void 0:r}function m(e){let t=p(e,`retry-after`);if(t===void 0)return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}function h(e,t=`x-block-number`){let n=p(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function g(e){return`get`in e&&typeof e.get==`function`}export{r as armTimeout,c as buildQueryString,l as buildRequestHeaders,u as fetchRequestor,h as readBlockNumberHeader,p as readHeader,f as readResponseBody,m as readRetryAfter,d as requestWithTimeout,i as validateTimeoutMs};
2
2
  //# sourceMappingURL=transport.js.map
@@ -1,2 +1,2 @@
1
- import{GalaSDKError as e}from"../classes/gala_sdk_error.js";import{hasValidEip55Casing as t}from"./eth_address.js";import{signHash as n}from"./signing.js";import{withPrivateKey as r}from"./chain_dto_signing.js";import{keccak_256 as i}from"@noble/hashes/sha3";const a=new TextEncoder,o=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,s=/^([A-Za-z_$][A-Za-z0-9_$]*)((?:\[(?:0|[1-9][0-9]*)?\])*)$/u,c=/^-?[0-9]+$/u,l=/^-?0x[0-9a-fA-F]+$/u,u=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`},{name:`salt`,type:`bytes32`}];function d(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function f(e){let t=/* @__PURE__ */ new Uint8Array(32),n=e<0n?e+(1n<<256n):e;for(let e=31;e>=0;--e)t[e]=Number(n&255n),n>>=8n;return t}function p(e){let t=e.slice(2),n=new Uint8Array(t.length/2);for(let e=0;e<n.length;e+=1)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function m(t,n){if(t instanceof Uint8Array)return t;if(typeof t==`string`&&/^0x(?:[0-9a-fA-F]{2})*$/u.test(t))return p(t);throw new e(`TYPED_DATA_NOT_HEX_BYTES`,{what:n})}function h(t,n){if(typeof t==`bigint`)return t;if(typeof t==`number`){if(!Number.isSafeInteger(t))throw new e(`TYPED_DATA_NOT_SAFE_INTEGER`,{what:n});return BigInt(t)}if(typeof t==`string`){if(c.test(t))return BigInt(t);if(l.test(t))return t.startsWith(`-`)?-BigInt(t.slice(1)):BigInt(t)}throw new e(`TYPED_DATA_NOT_INTEGER`,{what:n})}function g(t,n){if(typeof t!=`string`)throw new e(`TYPED_DATA_NOT_STRING`,{what:n});for(let r=0;r<t.length;r+=1){let i=t.charCodeAt(r);if(i>=55296&&i<=56319){let i=t.charCodeAt(r+1);if(!(i>=56320&&i<=57343))throw new e(`TYPED_DATA_UNPAIRED_SURROGATE`,{what:n});r+=1}else if(i>=56320&&i<=57343)throw new e(`TYPED_DATA_UNPAIRED_SURROGATE`,{what:n})}return a.encode(t)}function _(n){if(typeof n!=`string`||!/^0x[0-9a-fA-F]{40}$/u.test(n))throw new e(`TYPED_DATA_BAD_ADDRESS`,{});if(!t(n.slice(2)))throw new e(`TYPED_DATA_BAD_CHECKSUM`,{});return p(n)}function v(t){if(t===`string`)return e=>i(g(e,`string`));if(t===`bytes`)return e=>i(m(e,`bytes`));if(t===`bool`)return t=>{if(typeof t!=`boolean`)throw new e(`TYPED_DATA_NOT_BOOLEAN`,{});return f(t?1n:0n)};if(t===`address`)return e=>d([/* @__PURE__ */ new Uint8Array(12),_(e)]);let n=/^bytes([1-9][0-9]?)$/u.exec(t);if(n!==null){let r=Number(n[1]);return r>32||String(r)!==n[1]?void 0:n=>{let i=m(n,t);if(i.length!==r)throw new e(`TYPED_DATA_BYTES_LENGTH`,{type:t,width:r});return d([i,new Uint8Array(32-r)])}}let r=/^(u?)int([1-9][0-9]*)$/u.exec(t);if(r!==null){let n=Number(r[2]);if(n%8!=0||n>256||String(n)!==r[2])return;let i=r[1]===``,a=i?-(1n<<BigInt(n-1)):0n,o=i?(1n<<BigInt(n-1))-1n:(1n<<BigInt(n))-1n;return n=>{let r=h(n,t);if(r<a||r>o)throw new e(`TYPED_DATA_OUT_OF_BOUNDS`,{type:t});return f(r)}}}function y(t){let n=s.exec(t);if(n===null)throw new e(`TYPED_DATA_UNSUPPORTED_TYPE`,{type:t});let r=[...(n[2]??``).matchAll(/\[([0-9]*)\]/gu)].map(e=>e[1]===``?-1:Number(e[1]));return{base:n[1],dimensions:r}}function b(t,n){if(!Array.isArray(n))throw new e(`TYPED_DATA_FIELDS_NOT_LIST`,{typeName:t});let r=/* @__PURE__ */ new Set;return n.map(n=>{let i=n;if(typeof i?.name!=`string`||typeof i.type!=`string`)throw new e(`TYPED_DATA_FIELD_MALFORMED`,{typeName:t});if(!o.test(i.name))throw new e(`TYPED_DATA_INVALID_FIELD_NAME`,{name:i.name});if(r.has(i.name))throw new e(`TYPED_DATA_DUPLICATE_FIELD`,{name:i.name,typeName:t});r.add(i.name);let a=y(i.type),s=a.base===`uint`||a.base===`int`?`${a.base}256`:a.base;return{name:i.name,type:s+i.type.slice(a.base.length)}})}function x(t){let n=Object.keys(t),r=/* @__PURE__ */ new Map;for(let i of n){if(!o.test(i))throw new e(`TYPED_DATA_INVALID_TYPE_NAME`,{name:i});r.set(i,b(i,t[i]))}let s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let e of n)s.set(e,/* @__PURE__ */ new Set),c.set(e,/* @__PURE__ */ new Set);for(let[t,n]of r)for(let i of n){let{base:n}=y(i.type);if(n===t)throw new e(`TYPED_DATA_CIRCULAR_TYPE`,{typeName:t});if(v(n)===void 0){if(!r.has(n))throw new e(`TYPED_DATA_UNKNOWN_FIELD_TYPE`,{type:n,typeName:t});s.get(t)?.add(n),c.get(n)?.add(t)}}let l=n.filter(e=>c.get(e)?.size===0);if(l.length===0)throw new e(`TYPED_DATA_NO_PRIMARY_TYPE`,{});if(l.length>1)throw new e(`TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE`,{roots:l.join(`, `)});let u=l[0],f=/* @__PURE__ */ new Set,p=/* @__PURE__ */ new Set,m=t=>{if(f.has(t))throw new e(`TYPED_DATA_CIRCULAR_TYPE`,{typeName:t});if(!p.has(t)){f.add(t);for(let e of s.get(t)??[])m(e);f.delete(t),p.add(t)}};m(u);let h=(e,t)=>{for(let n of s.get(e)??[])t.has(n)||(t.add(n),h(n,t));return t},g=e=>`${e}(${(r.get(e)??[]).map(e=>`${e.type} ${e.name}`).join(`,`)})`,_=/* @__PURE__ */ new Map;for(let e of n){let t=[...h(e,/* @__PURE__ */ new Set)].filter(t=>t!==e).sort();_.set(e,i(a.encode([e,...t].map(g).join(``))))}let x=(t,n,r)=>{let a=t.dimensions[t.dimensions.length-1-r];if(a!==void 0){if(!Array.isArray(n))throw new e(`TYPED_DATA_ARRAY_EXPECTED`,{type:t.base});if(a!==-1&&a!==n.length)throw new e(`TYPED_DATA_ARRAY_LENGTH_MISMATCH`,{});return i(d(n.map(e=>x(t,e,r+1))))}let o=v(t.base);return o===void 0?S(t.base,n):o(n)};function S(t,n){let a=r.get(t),o=_.get(t);if(a===void 0||o===void 0)throw Error(`Internal error: no encoder for struct ${t}`);if(typeof n!=`object`||!n||Array.isArray(n))throw new e(`TYPED_DATA_STRUCT_NOT_OBJECT`,{typeName:t});let s=n,c=a.map(n=>{if(!Object.prototype.hasOwnProperty.call(s,n.name))throw new e(`TYPED_DATA_MISSING_FIELD`,{typeName:t,field:n.name});return x(y(n.type),s[n.name],0)});return i(d([o,...c]))}return{primaryType:u,hashStruct:S}}function S(t){if(typeof t!=`object`||!t||Array.isArray(t))throw new e(`TYPED_DATA_DOMAIN_NOT_OBJECT`,{});for(let n of Object.keys(t))if(!u.some(e=>e.name===n))throw new e(`TYPED_DATA_INVALID_DOMAIN_KEY`,{key:JSON.stringify(n)});return x({EIP712Domain:u.filter(e=>Object.prototype.hasOwnProperty.call(t,e.name))}).hashStruct(`EIP712Domain`,t)}function C(e){let t=S(e.domain),n=x(e.types),r=n.hashStruct(n.primaryType,e.message);return i(d([Uint8Array.of(25,1),t,r]))}async function w(e,t){let i=C(t);return r(e,e=>`0x${n(e,i)}`)}export{C as hashTypedData,w as signTypedDataPayload};
1
+ import{GalaSDKError as e}from"../classes/gala_sdk_error.js";import{hasValidEip55Casing as t}from"./eth_address.js";import{signHash as n}from"./signing.js";import{withPrivateKey as r}from"./chain_dto_signing.js";import{keccak_256 as i}from"@noble/hashes/sha3";const a=new TextEncoder,o=/^[A-Za-z_$][A-Za-z0-9_$]*$/u,s=/^([A-Za-z_$][A-Za-z0-9_$]*)((?:\[(?:0|[1-9][0-9]*)?\])*)$/u,c=/^-?[0-9]+$/u,l=/^-?0x[0-9a-fA-F]+$/u,u=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`},{name:`salt`,type:`bytes32`}];function d(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function f(e){let t=/* @__PURE__ */ new Uint8Array(32),n=e<0n?e+(1n<<256n):e;for(let e=31;e>=0;--e)t[e]=Number(n&255n),n>>=8n;return t}function p(e){let t=e.slice(2),n=new Uint8Array(t.length/2);for(let e=0;e<n.length;e+=1)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function m(t,n){if(t instanceof Uint8Array)return t;if(typeof t==`string`&&/^0x(?:[0-9a-fA-F]{2})*$/u.test(t))return p(t);throw new e(`TYPED_DATA_NOT_HEX_BYTES`,{what:n})}function h(t,n){if(typeof t==`bigint`)return t;if(typeof t==`number`){if(!Number.isSafeInteger(t))throw new e(`TYPED_DATA_NOT_SAFE_INTEGER`,{what:n});return BigInt(t)}if(typeof t==`string`){if(c.test(t))return BigInt(t);if(l.test(t))return t.startsWith(`-`)?-BigInt(t.slice(1)):BigInt(t)}throw new e(`TYPED_DATA_NOT_INTEGER`,{what:n})}function g(t,n){if(typeof t!=`string`)throw new e(`TYPED_DATA_NOT_STRING`,{what:n});for(let r=0;r<t.length;r+=1){let i=t.charCodeAt(r);if(i>=55296&&i<=56319){let i=t.charCodeAt(r+1);if(!(i>=56320&&i<=57343))throw new e(`TYPED_DATA_UNPAIRED_SURROGATE`,{what:n});r+=1}else if(i>=56320&&i<=57343)throw new e(`TYPED_DATA_UNPAIRED_SURROGATE`,{what:n})}return a.encode(t)}function _(n){if(typeof n!=`string`||!/^0x[0-9a-fA-F]{40}$/u.test(n))throw new e(`TYPED_DATA_BAD_ADDRESS`,{});if(!t(n.slice(2)))throw new e(`TYPED_DATA_BAD_CHECKSUM`,{});return p(n)}function v(t){if(t===`string`)return e=>i(g(e,`string`));if(t===`bytes`)return e=>i(m(e,`bytes`));if(t===`bool`)return t=>{if(typeof t!=`boolean`)throw new e(`TYPED_DATA_NOT_BOOLEAN`,{});return f(t?1n:0n)};if(t===`address`)return e=>d([/* @__PURE__ */ new Uint8Array(12),_(e)]);let n=/^bytes([1-9][0-9]?)$/u.exec(t);if(n!==null){let r=Number(n[1]);return r>32?void 0:n=>{let i=m(n,t);if(i.length!==r)throw new e(`TYPED_DATA_BYTES_LENGTH`,{type:t,width:r});return d([i,new Uint8Array(32-r)])}}let r=/^(u?)int([1-9][0-9]*)$/u.exec(t);if(r!==null){let n=Number(r[2]);if(n%8!=0||n>256||String(n)!==r[2])return;let i=r[1]===``,a=i?-(1n<<BigInt(n-1)):0n,o=i?(1n<<BigInt(n-1))-1n:(1n<<BigInt(n))-1n;return n=>{let r=h(n,t);if(r<a||r>o)throw new e(`TYPED_DATA_OUT_OF_BOUNDS`,{type:t});return f(r)}}}function y(t){let n=s.exec(t);if(n===null)throw new e(`TYPED_DATA_UNSUPPORTED_TYPE`,{type:t});let r=[...n[2].matchAll(/\[([0-9]*)\]/gu)].map(e=>e[1]===``?-1:Number(e[1]));return{base:n[1],dimensions:r}}function b(t,n){if(!Array.isArray(n))throw new e(`TYPED_DATA_FIELDS_NOT_LIST`,{typeName:t});let r=/* @__PURE__ */ new Set;return n.map(n=>{let i=n;if(typeof i?.name!=`string`||typeof i.type!=`string`)throw new e(`TYPED_DATA_FIELD_MALFORMED`,{typeName:t});if(!o.test(i.name))throw new e(`TYPED_DATA_INVALID_FIELD_NAME`,{name:i.name});if(r.has(i.name))throw new e(`TYPED_DATA_DUPLICATE_FIELD`,{name:i.name,typeName:t});r.add(i.name);let a=y(i.type),s=a.base===`uint`||a.base===`int`?`${a.base}256`:a.base;return{name:i.name,type:s+i.type.slice(a.base.length)}})}function x(t){let n=Object.keys(t),r=/* @__PURE__ */ new Map;for(let i of n){if(!o.test(i))throw new e(`TYPED_DATA_INVALID_TYPE_NAME`,{name:i});r.set(i,b(i,t[i]))}let s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let e of n)s.set(e,/* @__PURE__ */ new Set),c.set(e,/* @__PURE__ */ new Set);for(let[t,n]of r)for(let i of n){let{base:n}=y(i.type);if(n===t)throw new e(`TYPED_DATA_CIRCULAR_TYPE`,{typeName:t});if(v(n)===void 0){if(!r.has(n))throw new e(`TYPED_DATA_UNKNOWN_FIELD_TYPE`,{type:n,typeName:t});s.get(t)?.add(n),c.get(n)?.add(t)}}let l=n.filter(e=>c.get(e)?.size===0);if(l.length===0)throw new e(`TYPED_DATA_NO_PRIMARY_TYPE`,{});if(l.length>1)throw new e(`TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE`,{roots:l.join(`, `)});let u=l[0],f=/* @__PURE__ */ new Set,p=/* @__PURE__ */ new Set,m=t=>{if(f.has(t))throw new e(`TYPED_DATA_CIRCULAR_TYPE`,{typeName:t});if(!p.has(t)){f.add(t);for(let e of s.get(t))m(e);f.delete(t),p.add(t)}};m(u);let h=(e,t)=>{for(let n of s.get(e))t.has(n)||(t.add(n),h(n,t));return t},g=e=>`${e}(${r.get(e).map(e=>`${e.type} ${e.name}`).join(`,`)})`,_=/* @__PURE__ */ new Map;for(let e of n){let t=[...h(e,/* @__PURE__ */ new Set)].filter(t=>t!==e).sort();_.set(e,i(a.encode([e,...t].map(g).join(``))))}let x=(t,n,r)=>{let a=t.dimensions[t.dimensions.length-1-r];if(a!==void 0){if(!Array.isArray(n))throw new e(`TYPED_DATA_ARRAY_EXPECTED`,{type:t.base});if(a!==-1&&a!==n.length)throw new e(`TYPED_DATA_ARRAY_LENGTH_MISMATCH`,{});return i(d(n.map(e=>x(t,e,r+1))))}let o=v(t.base);return o===void 0?S(t.base,n):o(n)};function S(t,n){let a=r.get(t),o=_.get(t);if(typeof n!=`object`||!n||Array.isArray(n))throw new e(`TYPED_DATA_STRUCT_NOT_OBJECT`,{typeName:t});let s=n,c=a.map(n=>{if(!Object.prototype.hasOwnProperty.call(s,n.name))throw new e(`TYPED_DATA_MISSING_FIELD`,{typeName:t,field:n.name});return x(y(n.type),s[n.name],0)});return i(d([o,...c]))}return{primaryType:u,hashStruct:S}}function S(t){if(typeof t!=`object`||!t||Array.isArray(t))throw new e(`TYPED_DATA_DOMAIN_NOT_OBJECT`,{});for(let n of Object.keys(t))if(!u.some(e=>e.name===n))throw new e(`TYPED_DATA_INVALID_DOMAIN_KEY`,{key:JSON.stringify(n)});return x({EIP712Domain:u.filter(e=>Object.prototype.hasOwnProperty.call(t,e.name))}).hashStruct(`EIP712Domain`,t)}function C(e){let t=S(e.domain),n=x(e.types),r=n.hashStruct(n.primaryType,e.message);return i(d([Uint8Array.of(25,1),t,r]))}async function w(e,t){let i=C(t);return r(e,e=>`0x${n(e,i)}`)}export{C as hashTypedData,w as signTypedDataPayload};
2
2
  //# sourceMappingURL=typed_data.js.map