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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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
@@ -1 +1 @@
1
- {"version":3,"file":"typed_data.js","names":["textEncoder","IDENTIFIER","TYPE_SYNTAX","BIGINT_DECIMAL","BIGINT_HEX","DOMAIN_FIELDS","concat","out","parts","total","part","offset","bigintToWord","word","rest","value","index","hexToBytes","body","hex","toBytes","GalaSDKError","toBigInt","utf8","unit","next","addressBytes","hasValidEip55Casing","leafEncoder","base","keccak_256","fixed","width","bytes","integer","signed","lower","upper","number","parseType","match","type","dimensions","dimension","parseFields","rawFields","seen","field","raw","parsed","createStructEncoder","names","rawTypes","fields","name","children","parents","list","roots","primaryType","visiting","checked","checkCircular","child","dependencies","found","encodeOne","typeHashes","sorted","dep","encodeValue","depth","item","leaf","hashStruct","typeName","typeHash","record","words","hashDomain","domain","key","hashTypedData","domainHash","payload","encoder","structHash","signTypedDataPayload","digest","withPrivateKey","privateKey","signHash"],"sources":["../../../src/utils/typed_data.ts"],"sourcesContent":["/**\n * EIP-712 (`eth_signTypedData_v4`) hashing and signing for ARBITRARY dApp typed data, built on the\n * SDK's own primitives (`@noble/curves`, `@noble/hashes`) so a wallet can sign a dApp's typed-data\n * approval without ethers. It replaces the wallet's `new ethers.Wallet(key).signTypedData(...)`\n * and is pinned to it: the golden suite reproduces every fixture signature exactly and a seeded\n * differential fuzz compares the digest and signature with ethers for every supported type.\n *\n * Compared with ethers this encoder is deliberately STRICTER (it fails closed rather than coerce):\n * `bool` accepts only a boolean, numbers accept only safe integers / decimal or `0x` strings,\n * strings must be well-formed UTF-16, struct values must be objects whose fields are their own\n * properties, and every struct, field and type name must be a plain identifier. Anything ethers\n * accepts that is NOT in that set is refused here instead of being signed in a different shape\n * from what a user reviewed.\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { hasValidEip55Casing } from './eth_address.js';\nimport { signHash } from './signing.js';\nimport { withPrivateKey, type PrivateKeyInput } from './chain_dto_signing.js';\n\n/** A typed-data payload as `eth_signTypedData_v4` carries it, minus `primaryType` (it is inferred). */\nexport interface TypedDataPayload {\n domain: Record<string, unknown>;\n /** Struct definitions WITHOUT `EIP712Domain` (see `stripEip712DomainType`). */\n types: Record<string, readonly unknown[]>;\n message: Record<string, unknown>;\n}\n\ninterface TypedField {\n name: string;\n type: string;\n}\n\nconst textEncoder = new TextEncoder();\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;\nconst TYPE_SYNTAX = /^([A-Za-z_$][A-Za-z0-9_$]*)((?:\\[(?:0|[1-9][0-9]*)?\\])*)$/u;\nconst BIGINT_DECIMAL = /^-?[0-9]+$/u;\nconst BIGINT_HEX = /^-?0x[0-9a-fA-F]+$/u;\n\n/** The EIP-712 domain members and their types, in the order ethers (and the spec) hash them. */\nconst DOMAIN_FIELDS: readonly TypedField[] = [\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n];\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction bigintToWord(value: bigint): Uint8Array {\n const word = new Uint8Array(32);\n // Every caller has bounds-checked `value` against its Solidity type, so it fits in 256 bits.\n let rest = value < 0n ? value + (1n << 256n) : value;\n for (let index = 31; index >= 0; index -= 1) {\n word[index] = Number(rest & 0xffn);\n rest >>= 8n;\n }\n return word;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const body = hex.slice(2);\n const out = new Uint8Array(body.length / 2);\n for (let index = 0; index < out.length; index += 1) {\n out[index] = parseInt(body.slice(index * 2, index * 2 + 2), 16);\n }\n return out;\n}\n\nfunction toBytes(value: unknown, what: string): Uint8Array {\n if (value instanceof Uint8Array) return value;\n if (typeof value === 'string' && /^0x(?:[0-9a-fA-F]{2})*$/u.test(value)) return hexToBytes(value);\n throw new GalaSDKError('TYPED_DATA_NOT_HEX_BYTES', { what });\n}\n\nfunction toBigInt(value: unknown, what: string): bigint {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value))\n throw new GalaSDKError('TYPED_DATA_NOT_SAFE_INTEGER', { what });\n return BigInt(value);\n }\n if (typeof value === 'string') {\n if (BIGINT_DECIMAL.test(value)) return BigInt(value);\n if (BIGINT_HEX.test(value)) {\n return value.startsWith('-') ? -BigInt(value.slice(1)) : BigInt(value);\n }\n }\n throw new GalaSDKError('TYPED_DATA_NOT_INTEGER', { what });\n}\n\nfunction utf8(value: unknown, what: string): Uint8Array {\n if (typeof value !== 'string') throw new GalaSDKError('TYPED_DATA_NOT_STRING', { what });\n for (let index = 0; index < value.length; index += 1) {\n const unit = value.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n }\n return textEncoder.encode(value);\n}\n\n/** EIP-55: a mixed-case address must carry the right checksum; all-lower / all-upper is accepted. */\nfunction addressBytes(value: unknown): Uint8Array {\n if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{40}$/u.test(value)) {\n throw new GalaSDKError('TYPED_DATA_BAD_ADDRESS', {});\n }\n if (!hasValidEip55Casing(value.slice(2))) {\n throw new GalaSDKError('TYPED_DATA_BAD_CHECKSUM', {});\n }\n return hexToBytes(value);\n}\n\ntype LeafEncoder = (value: unknown) => Uint8Array;\n\n/** The encoder for a non-struct, non-array type, or undefined when `base` is not one. */\nfunction leafEncoder(base: string): LeafEncoder | undefined {\n if (base === 'string') return (value) => keccak_256(utf8(value, 'string'));\n if (base === 'bytes') return (value) => keccak_256(toBytes(value, 'bytes'));\n if (base === 'bool') {\n return (value) => {\n if (typeof value !== 'boolean') throw new GalaSDKError('TYPED_DATA_NOT_BOOLEAN', {});\n return bigintToWord(value ? 1n : 0n);\n };\n }\n if (base === 'address') {\n return (value) => concat([new Uint8Array(12), addressBytes(value)]);\n }\n const fixed = /^bytes([1-9][0-9]?)$/u.exec(base);\n if (fixed !== null) {\n const width = Number(fixed[1]);\n if (width > 32 || String(width) !== fixed[1]) return undefined;\n return (value) => {\n const bytes = toBytes(value, base);\n if (bytes.length !== width) {\n throw new GalaSDKError('TYPED_DATA_BYTES_LENGTH', { type: base, width });\n }\n return concat([bytes, new Uint8Array(32 - width)]);\n };\n }\n const integer = /^(u?)int([1-9][0-9]*)$/u.exec(base);\n if (integer !== null) {\n const width = Number(integer[2]);\n if (width % 8 !== 0 || width > 256 || String(width) !== integer[2]) return undefined;\n const signed = integer[1] === '';\n const lower = signed ? -(1n << BigInt(width - 1)) : 0n;\n const upper = signed ? (1n << BigInt(width - 1)) - 1n : (1n << BigInt(width)) - 1n;\n return (value) => {\n const number = toBigInt(value, base);\n if (number < lower || number > upper) {\n throw new GalaSDKError('TYPED_DATA_OUT_OF_BOUNDS', { type: base });\n }\n return bigintToWord(number);\n };\n }\n return undefined;\n}\n\ninterface ParsedType {\n base: string;\n /** Array suffixes outermost-last, e.g. `uint256[2][]` is `[2, -1]` (-1 = dynamic). */\n dimensions: number[];\n}\n\nfunction parseType(type: string): ParsedType {\n const match = TYPE_SYNTAX.exec(type);\n if (match === null) throw new GalaSDKError('TYPED_DATA_UNSUPPORTED_TYPE', { type });\n const dimensions = [...(match[2] ?? '').matchAll(/\\[([0-9]*)\\]/gu)].map((dimension) =>\n dimension[1] === '' ? -1 : Number(dimension[1]),\n );\n return { base: match[1] as string, dimensions };\n}\n\nfunction parseFields(typeName: string, rawFields: readonly unknown[]): TypedField[] {\n if (!Array.isArray(rawFields)) throw new GalaSDKError('TYPED_DATA_FIELDS_NOT_LIST', { typeName });\n const seen = new Set<string>();\n return rawFields.map((raw: unknown) => {\n const field = raw as { name?: unknown; type?: unknown } | null;\n if (typeof field?.name !== 'string' || typeof field.type !== 'string') {\n throw new GalaSDKError('TYPED_DATA_FIELD_MALFORMED', { typeName });\n }\n if (!IDENTIFIER.test(field.name)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_FIELD_NAME', { name: field.name });\n }\n if (seen.has(field.name)) {\n throw new GalaSDKError('TYPED_DATA_DUPLICATE_FIELD', { name: field.name, typeName });\n }\n seen.add(field.name);\n // A bare `int` / `uint` is the 256-bit type and is hashed as `int256` / `uint256`, like ethers.\n const parsed = parseType(field.type);\n const base =\n parsed.base === 'uint' || parsed.base === 'int' ? `${parsed.base}256` : parsed.base;\n return { name: field.name, type: base + field.type.slice(parsed.base.length) };\n });\n}\n\ninterface StructEncoder {\n primaryType: string;\n hashStruct: (typeName: string, value: unknown) => Uint8Array;\n}\n\n/**\n * Builds the struct encoder for a set of type definitions: validates the type graph (unknown or\n * circular references, duplicate fields) and infers the primary type as the single type no other\n * type references, exactly like ethers' `TypedDataEncoder`.\n */\nfunction createStructEncoder(rawTypes: Record<string, readonly unknown[]>): StructEncoder {\n const names = Object.keys(rawTypes);\n const fields = new Map<string, TypedField[]>();\n for (const name of names) {\n if (!IDENTIFIER.test(name)) throw new GalaSDKError('TYPED_DATA_INVALID_TYPE_NAME', { name });\n fields.set(name, parseFields(name, rawTypes[name] as readonly unknown[]));\n }\n\n const children = new Map<string, Set<string>>();\n const parents = new Map<string, Set<string>>();\n for (const name of names) {\n children.set(name, new Set());\n parents.set(name, new Set());\n }\n for (const [name, list] of fields) {\n for (const field of list) {\n const { base } = parseType(field.type);\n if (base === name) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (leafEncoder(base) !== undefined) continue;\n if (!fields.has(base)) {\n throw new GalaSDKError('TYPED_DATA_UNKNOWN_FIELD_TYPE', { type: base, typeName: name });\n }\n children.get(name)?.add(base);\n parents.get(base)?.add(name);\n }\n }\n\n const roots = names.filter((name) => parents.get(name)?.size === 0);\n if (roots.length === 0) throw new GalaSDKError('TYPED_DATA_NO_PRIMARY_TYPE', {});\n if (roots.length > 1) {\n throw new GalaSDKError('TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE', { roots: roots.join(', ') });\n }\n const primaryType = roots[0] as string;\n\n const visiting = new Set<string>();\n const checked = new Set<string>();\n const checkCircular = (name: string): void => {\n if (visiting.has(name)) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (checked.has(name)) return;\n visiting.add(name);\n for (const child of children.get(name) ?? []) checkCircular(child);\n visiting.delete(name);\n checked.add(name);\n };\n checkCircular(primaryType);\n\n const dependencies = (name: string, found: Set<string>): Set<string> => {\n for (const child of children.get(name) ?? []) {\n if (!found.has(child)) {\n found.add(child);\n dependencies(child, found);\n }\n }\n return found;\n };\n const encodeOne = (name: string): string =>\n `${name}(${(fields.get(name) ?? []).map((field) => `${field.type} ${field.name}`).join(',')})`;\n const typeHashes = new Map<string, Uint8Array>();\n for (const name of names) {\n const sorted = [...dependencies(name, new Set())].filter((dep) => dep !== name).sort();\n typeHashes.set(name, keccak_256(textEncoder.encode([name, ...sorted].map(encodeOne).join(''))));\n }\n\n const encodeValue = (parsed: ParsedType, value: unknown, depth: number): Uint8Array => {\n // The LAST bracket written is the outermost array: `uint8[][2]` is two `uint8[]`.\n const dimension = parsed.dimensions[parsed.dimensions.length - 1 - depth];\n if (dimension !== undefined) {\n if (!Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_EXPECTED', { type: parsed.base });\n }\n if (dimension !== -1 && dimension !== value.length) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_LENGTH_MISMATCH', {});\n }\n return keccak_256(concat(value.map((item) => encodeValue(parsed, item, depth + 1))));\n }\n const leaf = leafEncoder(parsed.base);\n if (leaf !== undefined) return leaf(value);\n return hashStruct(parsed.base, value);\n };\n\n function hashStruct(typeName: string, value: unknown): Uint8Array {\n const list = fields.get(typeName);\n const typeHash = typeHashes.get(typeName);\n if (list === undefined || typeHash === undefined) {\n // createStructEncoder has already validated every struct name this is called with.\n throw new Error(`Internal error: no encoder for struct ${typeName}`);\n }\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_STRUCT_NOT_OBJECT', { typeName });\n }\n const record = value as Record<string, unknown>;\n const words = list.map((field) => {\n if (!Object.prototype.hasOwnProperty.call(record, field.name)) {\n throw new GalaSDKError('TYPED_DATA_MISSING_FIELD', { typeName, field: field.name });\n }\n // Struct-valued fields are encoded to their 32-byte struct hash by encodeValue.\n return encodeValue(parseType(field.type), record[field.name], 0);\n });\n return keccak_256(concat([typeHash, ...words]));\n }\n\n return { primaryType, hashStruct };\n}\n\nfunction hashDomain(domain: Record<string, unknown>): Uint8Array {\n if (domain === null || typeof domain !== 'object' || Array.isArray(domain)) {\n throw new GalaSDKError('TYPED_DATA_DOMAIN_NOT_OBJECT', {});\n }\n for (const key of Object.keys(domain)) {\n if (!DOMAIN_FIELDS.some((field) => field.name === key)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_DOMAIN_KEY', { key: JSON.stringify(key) });\n }\n }\n const present = DOMAIN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(domain, field.name),\n );\n const encoder = createStructEncoder({ EIP712Domain: present });\n return encoder.hashStruct('EIP712Domain', domain);\n}\n\n/**\n * The EIP-712 digest `keccak256(0x1901 || domainSeparator || hashStruct(primaryType, message))`\n * that a wallet signs for `eth_signTypedData_v4`. The primary type is inferred, as ethers does.\n *\n * @throws GalaSDKError (`TYPED_DATA_*`) for any type graph or value it cannot encode\n * exactly (see the module note on strictness).\n */\nexport function hashTypedData(payload: TypedDataPayload): Uint8Array {\n const domainHash = hashDomain(payload.domain);\n const encoder = createStructEncoder(payload.types);\n const structHash = encoder.hashStruct(encoder.primaryType, payload.message);\n return keccak_256(concat([Uint8Array.of(0x19, 0x01), domainHash, structHash]));\n}\n\n/**\n * Signs a dApp's EIP-712 typed-data approval (the wallet's `signTypedMessage` path), replacing\n * `new ethers.Wallet(key).signTypedData(domain, types, message)`. `types` must already have\n * `EIP712Domain` removed (`stripEip712DomainType`).\n *\n * @returns `0x` + r + s + v with `v` = `0x1b`/`0x1c` (27/28): ethers' serialized signature form,\n * recoverable with `verifyTypedData` / `eth_signTypedData_v4` verifiers. Rejects (never throws\n * synchronously) on invalid input.\n */\nexport async function signTypedDataPayload(\n privateKey: PrivateKeyInput,\n payload: TypedDataPayload,\n): Promise<string> {\n const digest = hashTypedData(payload);\n return withPrivateKey(privateKey, (key) => `0x${signHash(key, digest)}`);\n}\n"],"mappings":"mQAiCA,MAAMA,EAAc,IAAI,YAClBC,EAAa,8BACbC,EAAc,6DACdC,EAAiB,cACjBC,EAAa,sBAGbC,EAAuC,CAC3C,CAAE,KAAM,OAAQ,KAAM,QAAS,EAC/B,CAAE,KAAM,UAAW,KAAM,QAAS,EAClC,CAAE,KAAM,UAAW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ClC,GAAI,CAAC3E,EAAc,KAAM,GAAU0C,EAAM,OAASkC,CAAG,EACnD,MAAM,IAAI5D,EAAa,gCAAiC,CAAE,IAAK,KAAK,UAAU4D,CAAG,CAAE,CAAC,EAOxF,OADgB/B,EAAoB,CAAE,aAHtB7C,EAAc,OAAQ,GACpC,OAAO,UAAU,eAAe,KAAK2E,EAAQjC,EAAM,IAAI,CAEC,CAAE,CAC/C,CAAC,CAAC,WAAW,eAAgBiC,CAAM,CAClD,CASA,SAAgBE,EAAc,EAAuC,CACnE,IAAMC,EAAaJ,EAAWK,EAAQ,MAAM,EACtCC,EAAUnC,EAAoBkC,EAAQ,KAAK,EAC3CE,EAAaD,EAAQ,WAAWA,EAAQ,YAAaD,EAAQ,OAAO,EAC1E,OAAOtD,EAAWxB,EAAO,CAAC,WAAW,GAAG,GAAM,CAAI,EAAG6E,EAAYG,CAAU,CAAC,CAAC,CAC/E,CAWA,eAAsBC,EACpB,EACA,EACiB,CACjB,IAAMC,EAASN,EAAcE,CAAO,EACpC,OAAOK,EAAeC,EAAa,GAAQ,KAAKC,EAASV,EAAKO,CAAM,GAAG,CACzE"}
1
+ {"version":3,"file":"typed_data.js","names":["textEncoder","IDENTIFIER","TYPE_SYNTAX","BIGINT_DECIMAL","BIGINT_HEX","DOMAIN_FIELDS","concat","out","parts","total","part","offset","bigintToWord","word","rest","value","index","hexToBytes","body","hex","toBytes","GalaSDKError","toBigInt","utf8","unit","next","addressBytes","hasValidEip55Casing","leafEncoder","base","keccak_256","fixed","width","bytes","integer","signed","lower","upper","number","parseType","match","type","dimensions","dimension","parseFields","rawFields","seen","field","raw","parsed","createStructEncoder","names","rawTypes","fields","name","children","parents","list","roots","primaryType","visiting","checked","checkCircular","child","dependencies","found","encodeOne","typeHashes","sorted","dep","encodeValue","depth","item","leaf","hashStruct","typeName","typeHash","record","words","hashDomain","domain","key","hashTypedData","domainHash","payload","encoder","structHash","signTypedDataPayload","digest","withPrivateKey","privateKey","signHash"],"sources":["../../../src/utils/typed_data.ts"],"sourcesContent":["/**\n * EIP-712 (`eth_signTypedData_v4`) hashing and signing for ARBITRARY dApp typed data, built on the\n * SDK's own primitives (`@noble/curves`, `@noble/hashes`) so a wallet can sign a dApp's typed-data\n * approval without ethers. It replaces the wallet's `new ethers.Wallet(key).signTypedData(...)`\n * and is pinned to it: the golden suite reproduces every fixture signature exactly and a seeded\n * differential fuzz compares the digest and signature with ethers for every supported type.\n *\n * Compared with ethers this encoder is deliberately STRICTER (it fails closed rather than coerce):\n * `bool` accepts only a boolean, numbers accept only safe integers / decimal or `0x` strings,\n * strings must be well-formed UTF-16, struct values must be objects whose fields are their own\n * properties, and every struct, field and type name must be a plain identifier. Anything ethers\n * accepts that is NOT in that set is refused here instead of being signed in a different shape\n * from what a user reviewed.\n */\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { hasValidEip55Casing } from './eth_address.js';\nimport { signHash } from './signing.js';\nimport { withPrivateKey, type PrivateKeyInput } from './chain_dto_signing.js';\n\n/** A typed-data payload as `eth_signTypedData_v4` carries it, minus `primaryType` (it is inferred). */\nexport interface TypedDataPayload {\n domain: Record<string, unknown>;\n /** Struct definitions WITHOUT `EIP712Domain` (see `stripEip712DomainType`). */\n types: Record<string, readonly unknown[]>;\n message: Record<string, unknown>;\n}\n\ninterface TypedField {\n name: string;\n type: string;\n}\n\nconst textEncoder = new TextEncoder();\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;\nconst TYPE_SYNTAX = /^([A-Za-z_$][A-Za-z0-9_$]*)((?:\\[(?:0|[1-9][0-9]*)?\\])*)$/u;\nconst BIGINT_DECIMAL = /^-?[0-9]+$/u;\nconst BIGINT_HEX = /^-?0x[0-9a-fA-F]+$/u;\n\n/** The EIP-712 domain members and their types, in the order ethers (and the spec) hash them. */\nconst DOMAIN_FIELDS: readonly TypedField[] = [\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n { name: 'salt', type: 'bytes32' },\n];\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction bigintToWord(value: bigint): Uint8Array {\n const word = new Uint8Array(32);\n // Every caller has bounds-checked `value` against its Solidity type, so it fits in 256 bits.\n let rest = value < 0n ? value + (1n << 256n) : value;\n for (let index = 31; index >= 0; index -= 1) {\n word[index] = Number(rest & 0xffn);\n rest >>= 8n;\n }\n return word;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const body = hex.slice(2);\n const out = new Uint8Array(body.length / 2);\n for (let index = 0; index < out.length; index += 1) {\n out[index] = parseInt(body.slice(index * 2, index * 2 + 2), 16);\n }\n return out;\n}\n\nfunction toBytes(value: unknown, what: string): Uint8Array {\n if (value instanceof Uint8Array) return value;\n if (typeof value === 'string' && /^0x(?:[0-9a-fA-F]{2})*$/u.test(value)) return hexToBytes(value);\n throw new GalaSDKError('TYPED_DATA_NOT_HEX_BYTES', { what });\n}\n\nfunction toBigInt(value: unknown, what: string): bigint {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number') {\n if (!Number.isSafeInteger(value))\n throw new GalaSDKError('TYPED_DATA_NOT_SAFE_INTEGER', { what });\n return BigInt(value);\n }\n if (typeof value === 'string') {\n if (BIGINT_DECIMAL.test(value)) return BigInt(value);\n if (BIGINT_HEX.test(value)) {\n return value.startsWith('-') ? -BigInt(value.slice(1)) : BigInt(value);\n }\n }\n throw new GalaSDKError('TYPED_DATA_NOT_INTEGER', { what });\n}\n\nfunction utf8(value: unknown, what: string): Uint8Array {\n if (typeof value !== 'string') throw new GalaSDKError('TYPED_DATA_NOT_STRING', { what });\n for (let index = 0; index < value.length; index += 1) {\n const unit = value.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n throw new GalaSDKError('TYPED_DATA_UNPAIRED_SURROGATE', { what });\n }\n }\n return textEncoder.encode(value);\n}\n\n/** EIP-55: a mixed-case address must carry the right checksum; all-lower / all-upper is accepted. */\nfunction addressBytes(value: unknown): Uint8Array {\n if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{40}$/u.test(value)) {\n throw new GalaSDKError('TYPED_DATA_BAD_ADDRESS', {});\n }\n if (!hasValidEip55Casing(value.slice(2))) {\n throw new GalaSDKError('TYPED_DATA_BAD_CHECKSUM', {});\n }\n return hexToBytes(value);\n}\n\ntype LeafEncoder = (value: unknown) => Uint8Array;\n\n/** The encoder for a non-struct, non-array type, or undefined when `base` is not one. */\nfunction leafEncoder(base: string): LeafEncoder | undefined {\n if (base === 'string') return (value) => keccak_256(utf8(value, 'string'));\n if (base === 'bytes') return (value) => keccak_256(toBytes(value, 'bytes'));\n if (base === 'bool') {\n return (value) => {\n if (typeof value !== 'boolean') throw new GalaSDKError('TYPED_DATA_NOT_BOOLEAN', {});\n return bigintToWord(value ? 1n : 0n);\n };\n }\n if (base === 'address') {\n return (value) => concat([new Uint8Array(12), addressBytes(value)]);\n }\n const fixed = /^bytes([1-9][0-9]?)$/u.exec(base);\n if (fixed !== null) {\n const width = Number(fixed[1]);\n // The pattern above admits no leading zero, so `String(width)` is always the digits written.\n if (width > 32) return undefined;\n return (value) => {\n const bytes = toBytes(value, base);\n if (bytes.length !== width) {\n throw new GalaSDKError('TYPED_DATA_BYTES_LENGTH', { type: base, width });\n }\n return concat([bytes, new Uint8Array(32 - width)]);\n };\n }\n const integer = /^(u?)int([1-9][0-9]*)$/u.exec(base);\n if (integer !== null) {\n const width = Number(integer[2]);\n if (width % 8 !== 0 || width > 256 || String(width) !== integer[2]) return undefined;\n const signed = integer[1] === '';\n const lower = signed ? -(1n << BigInt(width - 1)) : 0n;\n const upper = signed ? (1n << BigInt(width - 1)) - 1n : (1n << BigInt(width)) - 1n;\n return (value) => {\n const number = toBigInt(value, base);\n if (number < lower || number > upper) {\n throw new GalaSDKError('TYPED_DATA_OUT_OF_BOUNDS', { type: base });\n }\n return bigintToWord(number);\n };\n }\n return undefined;\n}\n\ninterface ParsedType {\n base: string;\n /** Array suffixes outermost-last, e.g. `uint256[2][]` is `[2, -1]` (-1 = dynamic). */\n dimensions: number[];\n}\n\nfunction parseType(type: string): ParsedType {\n const match = TYPE_SYNTAX.exec(type);\n if (match === null) throw new GalaSDKError('TYPED_DATA_UNSUPPORTED_TYPE', { type });\n // Group 2 of TYPE_SYNTAX is `(...)*` around the whole suffix run, so it always participates.\n const dimensions = [...(match[2] as string).matchAll(/\\[([0-9]*)\\]/gu)].map((dimension) =>\n dimension[1] === '' ? -1 : Number(dimension[1]),\n );\n return { base: match[1] as string, dimensions };\n}\n\nfunction parseFields(typeName: string, rawFields: readonly unknown[]): TypedField[] {\n if (!Array.isArray(rawFields)) throw new GalaSDKError('TYPED_DATA_FIELDS_NOT_LIST', { typeName });\n const seen = new Set<string>();\n return rawFields.map((raw: unknown) => {\n const field = raw as { name?: unknown; type?: unknown } | null;\n if (typeof field?.name !== 'string' || typeof field.type !== 'string') {\n throw new GalaSDKError('TYPED_DATA_FIELD_MALFORMED', { typeName });\n }\n if (!IDENTIFIER.test(field.name)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_FIELD_NAME', { name: field.name });\n }\n if (seen.has(field.name)) {\n throw new GalaSDKError('TYPED_DATA_DUPLICATE_FIELD', { name: field.name, typeName });\n }\n seen.add(field.name);\n // A bare `int` / `uint` is the 256-bit type and is hashed as `int256` / `uint256`, like ethers.\n const parsed = parseType(field.type);\n const base =\n parsed.base === 'uint' || parsed.base === 'int' ? `${parsed.base}256` : parsed.base;\n return { name: field.name, type: base + field.type.slice(parsed.base.length) };\n });\n}\n\ninterface StructEncoder {\n primaryType: string;\n hashStruct: (typeName: string, value: unknown) => Uint8Array;\n}\n\n/**\n * Builds the struct encoder for a set of type definitions: validates the type graph (unknown or\n * circular references, duplicate fields) and infers the primary type as the single type no other\n * type references, exactly like ethers' `TypedDataEncoder`.\n */\nfunction createStructEncoder(rawTypes: Record<string, readonly unknown[]>): StructEncoder {\n const names = Object.keys(rawTypes);\n const fields = new Map<string, TypedField[]>();\n for (const name of names) {\n if (!IDENTIFIER.test(name)) throw new GalaSDKError('TYPED_DATA_INVALID_TYPE_NAME', { name });\n fields.set(name, parseFields(name, rawTypes[name] as readonly unknown[]));\n }\n\n const children = new Map<string, Set<string>>();\n const parents = new Map<string, Set<string>>();\n for (const name of names) {\n children.set(name, new Set());\n parents.set(name, new Set());\n }\n for (const [name, list] of fields) {\n for (const field of list) {\n const { base } = parseType(field.type);\n if (base === name) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (leafEncoder(base) !== undefined) continue;\n if (!fields.has(base)) {\n throw new GalaSDKError('TYPED_DATA_UNKNOWN_FIELD_TYPE', { type: base, typeName: name });\n }\n children.get(name)?.add(base);\n parents.get(base)?.add(name);\n }\n }\n\n const roots = names.filter((name) => parents.get(name)?.size === 0);\n if (roots.length === 0) throw new GalaSDKError('TYPED_DATA_NO_PRIMARY_TYPE', {});\n if (roots.length > 1) {\n throw new GalaSDKError('TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE', { roots: roots.join(', ') });\n }\n const primaryType = roots[0] as string;\n\n const visiting = new Set<string>();\n const checked = new Set<string>();\n const checkCircular = (name: string): void => {\n if (visiting.has(name)) throw new GalaSDKError('TYPED_DATA_CIRCULAR_TYPE', { typeName: name });\n if (checked.has(name)) return;\n visiting.add(name);\n // `children` holds an entry for every name, and `name` is always one of them.\n for (const child of children.get(name) as Set<string>) checkCircular(child);\n visiting.delete(name);\n checked.add(name);\n };\n checkCircular(primaryType);\n\n const dependencies = (name: string, found: Set<string>): Set<string> => {\n for (const child of children.get(name) as Set<string>) {\n if (!found.has(child)) {\n found.add(child);\n dependencies(child, found);\n }\n }\n return found;\n };\n const encodeOne = (name: string): string =>\n `${name}(${(fields.get(name) as TypedField[]).map((field) => `${field.type} ${field.name}`).join(',')})`;\n const typeHashes = new Map<string, Uint8Array>();\n for (const name of names) {\n const sorted = [...dependencies(name, new Set())].filter((dep) => dep !== name).sort();\n typeHashes.set(name, keccak_256(textEncoder.encode([name, ...sorted].map(encodeOne).join(''))));\n }\n\n const encodeValue = (parsed: ParsedType, value: unknown, depth: number): Uint8Array => {\n // The LAST bracket written is the outermost array: `uint8[][2]` is two `uint8[]`.\n const dimension = parsed.dimensions[parsed.dimensions.length - 1 - depth];\n if (dimension !== undefined) {\n if (!Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_EXPECTED', { type: parsed.base });\n }\n if (dimension !== -1 && dimension !== value.length) {\n throw new GalaSDKError('TYPED_DATA_ARRAY_LENGTH_MISMATCH', {});\n }\n return keccak_256(concat(value.map((item) => encodeValue(parsed, item, depth + 1))));\n }\n const leaf = leafEncoder(parsed.base);\n if (leaf !== undefined) return leaf(value);\n return hashStruct(parsed.base, value);\n };\n\n function hashStruct(typeName: string, value: unknown): Uint8Array {\n // createStructEncoder has already validated every struct name this is called with (the\n // primary type, the domain type, and each field base that is not a leaf type).\n const list = fields.get(typeName) as TypedField[];\n const typeHash = typeHashes.get(typeName) as Uint8Array;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new GalaSDKError('TYPED_DATA_STRUCT_NOT_OBJECT', { typeName });\n }\n const record = value as Record<string, unknown>;\n const words = list.map((field) => {\n if (!Object.prototype.hasOwnProperty.call(record, field.name)) {\n throw new GalaSDKError('TYPED_DATA_MISSING_FIELD', { typeName, field: field.name });\n }\n // Struct-valued fields are encoded to their 32-byte struct hash by encodeValue.\n return encodeValue(parseType(field.type), record[field.name], 0);\n });\n return keccak_256(concat([typeHash, ...words]));\n }\n\n return { primaryType, hashStruct };\n}\n\nfunction hashDomain(domain: Record<string, unknown>): Uint8Array {\n if (domain === null || typeof domain !== 'object' || Array.isArray(domain)) {\n throw new GalaSDKError('TYPED_DATA_DOMAIN_NOT_OBJECT', {});\n }\n for (const key of Object.keys(domain)) {\n if (!DOMAIN_FIELDS.some((field) => field.name === key)) {\n throw new GalaSDKError('TYPED_DATA_INVALID_DOMAIN_KEY', { key: JSON.stringify(key) });\n }\n }\n const present = DOMAIN_FIELDS.filter((field) =>\n Object.prototype.hasOwnProperty.call(domain, field.name),\n );\n const encoder = createStructEncoder({ EIP712Domain: present });\n return encoder.hashStruct('EIP712Domain', domain);\n}\n\n/**\n * The EIP-712 digest `keccak256(0x1901 || domainSeparator || hashStruct(primaryType, message))`\n * that a wallet signs for `eth_signTypedData_v4`. The primary type is inferred, as ethers does.\n *\n * @throws GalaSDKError (`TYPED_DATA_*`) for any type graph or value it cannot encode\n * exactly (see the module note on strictness).\n */\nexport function hashTypedData(payload: TypedDataPayload): Uint8Array {\n const domainHash = hashDomain(payload.domain);\n const encoder = createStructEncoder(payload.types);\n const structHash = encoder.hashStruct(encoder.primaryType, payload.message);\n return keccak_256(concat([Uint8Array.of(0x19, 0x01), domainHash, structHash]));\n}\n\n/**\n * Signs a dApp's EIP-712 typed-data approval (the wallet's `signTypedMessage` path), replacing\n * `new ethers.Wallet(key).signTypedData(domain, types, message)`. `types` must already have\n * `EIP712Domain` removed (`stripEip712DomainType`).\n *\n * @returns `0x` + r + s + v with `v` = `0x1b`/`0x1c` (27/28): ethers' serialized signature form,\n * recoverable with `verifyTypedData` / `eth_signTypedData_v4` verifiers. Rejects (never throws\n * synchronously) on invalid input.\n */\nexport async function signTypedDataPayload(\n privateKey: PrivateKeyInput,\n payload: TypedDataPayload,\n): Promise<string> {\n const digest = hashTypedData(payload);\n return withPrivateKey(privateKey, (key) => `0x${signHash(key, digest)}`);\n}\n"],"mappings":"mQAiCA,MAAMA,EAAc,IAAI,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O,OAAO,KAAKD,CAAM,EAClC,GAAI,CAAC3E,EAAc,KAAM,GAAU0C,EAAM,OAASkC,CAAG,EACnD,MAAM,IAAI5D,EAAa,gCAAiC,CAAE,IAAK,KAAK,UAAU4D,CAAG,CAAE,CAAC,EAOxF,OADgB/B,EAAoB,CAAE,aAHtB7C,EAAc,OAAQ,GACpC,OAAO,UAAU,eAAe,KAAK2E,EAAQjC,EAAM,IAAI,CAEC,CAAE,CAC/C,CAAC,CAAC,WAAW,eAAgBiC,CAAM,CAClD,CASA,SAAgBE,EAAc,EAAuC,CACnE,IAAMC,EAAaJ,EAAWK,EAAQ,MAAM,EACtCC,EAAUnC,EAAoBkC,EAAQ,KAAK,EAC3CE,EAAaD,EAAQ,WAAWA,EAAQ,YAAaD,EAAQ,OAAO,EAC1E,OAAOtD,EAAWxB,EAAO,CAAC,WAAW,GAAG,GAAM,CAAI,EAAG6E,EAAYG,CAAU,CAAC,CAAC,CAC/E,CAWA,eAAsBC,EACpB,EACA,EACiB,CACjB,IAAMC,EAASN,EAAcE,CAAO,EACpC,OAAOK,EAAeC,EAAa,GAAQ,KAAKC,EAASV,EAAKO,CAAM,GAAG,CACzE"}
@@ -1 +1 @@
1
- {"version":3,"file":"unique_key.js","names":["DEFAULT_UNIQUE_KEY_PREFIX","UNIQUE_KEY_PREFIX_PATTERN","resolveUniqueKeyPrefix","prefix","GalaSDKError","assertUniqueKey","isValidUniqueKey","uniqueKey","randomUuidV4","source","bytes","hex","value","index","byte","text","createUniqueKey"],"sources":["../../../src/utils/unique_key.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { isValidUniqueKey } from './unique_key_syntax.js';\n\n/**\n * The `uniqueKey` prefix frontend_v2 and wallet_extension have always sent\n * (`galaswap-operation-<uuid>`). defi-backend does not depend on it: the chain-write verifier\n * only requires a non-empty key of at most 256 characters, and apply-results accepts\n * `[A-Za-z0-9._:-]{1,128}`; the only code that mints a prefixed key itself is the server-side v1\n * trade builder, which nothing reads back by prefix.\n */\nexport const DEFAULT_UNIQUE_KEY_PREFIX = 'galaswap-operation-';\n\n/** Options shared by the services that mint `uniqueKey`s for writes. */\nexport interface UniqueKeyOptions {\n /**\n * Prefix of every minted `uniqueKey` (`<prefix><uuid>`). Defaults to\n * `DEFAULT_UNIQUE_KEY_PREFIX` (`galaswap-operation-`).\n */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/** A canonical UUID is 36 characters; the apply-results key limit is 128. */\nconst MAX_UNIQUE_KEY_PREFIX_LENGTH = 128 - 36;\nconst UNIQUE_KEY_PREFIX_PATTERN = /^[A-Za-z0-9._:-]*$/u;\n\n/**\n * Validates a caller-supplied `uniqueKey` prefix. The whole key (`<prefix><uuid>`) must stay a\n * valid apply-results key, otherwise `confirm()` could never read the outcome of the write.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY_PREFIX` when the prefix has characters outside\n * `A-Za-z0-9._:-` or is longer than 92 characters.\n */\nexport function resolveUniqueKeyPrefix(prefix: string | undefined): string {\n if (prefix === undefined) return DEFAULT_UNIQUE_KEY_PREFIX;\n if (!UNIQUE_KEY_PREFIX_PATTERN.test(prefix) || prefix.length > MAX_UNIQUE_KEY_PREFIX_LENGTH) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY_PREFIX', {\n uniqueKeyPrefix: prefix,\n maxLength: MAX_UNIQUE_KEY_PREFIX_LENGTH,\n });\n }\n return prefix;\n}\n\n/**\n * Validates a caller-supplied write `uniqueKey`: 1 to 128 characters of `A-Za-z0-9._:-`, the\n * shape the apply-results route accepts, so the write's outcome can always be read back with\n * `confirm()`. A key is one attempt's identity: reuse it only to retry that same attempt.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY` otherwise.\n */\nexport function assertUniqueKey(uniqueKey: string): void {\n if (!isValidUniqueKey(uniqueKey)) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY', { uniqueKey: String(uniqueKey) });\n }\n}\n\n/** The part of `globalThis.crypto` a uniqueKey needs: the one CSPRNG every target can offer. */\ninterface RandomValuesSource {\n getRandomValues?: ((array: Uint8Array) => unknown) | undefined;\n}\n\n/**\n * A random version-4 UUID (RFC 9562) in the canonical lowercase `8-4-4-4-12` form, byte for byte\n * the shape `crypto.randomUUID()` returns, built from `crypto.getRandomValues`. `randomUUID` is\n * NOT used: React Native's Hermes has no `crypto.randomUUID`, so a write would fail with\n * \"undefined is not a function\", while `getRandomValues` is what browsers, Node (>= 19 as a\n * global), MV3 service workers and Hermes with `react-native-get-random-values` all provide.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when there is no `getRandomValues`: a key minted from\n * `Math.random` could collide with another attempt's, so the SDK refuses rather than degrade.\n */\nfunction randomUuidV4(): string {\n const source = (globalThis as { crypto?: RandomValuesSource | undefined }).crypto;\n if (typeof source?.getRandomValues !== 'function') {\n throw new GalaSDKError('CSPRNG_UNAVAILABLE', {});\n }\n // Filled in place: a polyfill is not relied on to return the array.\n const bytes = new Uint8Array(16);\n source.getRandomValues(bytes);\n const hex: string[] = [];\n bytes.forEach((byte, index) => {\n // Version nibble 4 in byte 6, variant bits 10 in byte 8; everything else stays random.\n const value = index === 6 ? (byte & 0x0f) | 0x40 : index === 8 ? (byte & 0x3f) | 0x80 : byte;\n hex.push(value.toString(16).padStart(2, '0'));\n });\n const text = hex.join('');\n return [\n text.slice(0, 8),\n text.slice(8, 12),\n text.slice(12, 16),\n text.slice(16, 20),\n text.slice(20),\n ].join('-');\n}\n\n/**\n * A fresh per-attempt key: `<prefix><random UUID>`, the UUID a random version-4 one.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when the platform has no `crypto.getRandomValues`\n * (install a polyfill such as `react-native-get-random-values` on React Native).\n */\nexport function createUniqueKey(prefix: string): string {\n return `${prefix}${randomUuidV4()}`;\n}\n"],"mappings":"sHAUA,MAAaA,EAA4B,sBAanCC,EAA4B,sBASlC,SAAgBC,EAAuB,EAAoC,CACzE,GAAIC,IAAW,IAAA,GAAW,OAAOH,EACjC,GAAI,CAACC,EAA0B,KAAKE,CAAM,GAAKA,EAAO,OAAS,GAC7D,MAAM,IAAIC,EAAa,4BAA6B,CAClD,gBAAiBD,EACjB,UAAW,EACb,CAAC,EAEH,OAAOA,CACT,CASA,SAAgBE,EAAgB,EAAyB,CACvD,GAAI,CAACC,EAAiBC,CAAS,EAC7B,MAAM,IAAIH,EAAa,qBAAsB,CAAE,UAAW,OAAOG,CAAS,CAAE,CAAC,CAEjF,CAiBA,SAASC,GAAuB,CAC9B,IAAMC,EAAU,WAA2D,OAC3E,GAAI,OAAOA,GAAQ,iBAAoB,WACrC,MAAM,IAAIL,EAAa,qBAAsB,CAAC,CAAC,EAGjD,IAAMM,kBAAQ,IAAI,WAAW,EAAE,EAC/BD,EAAO,gBAAgBC,CAAK,EAC5B,IAAMC,EAAgB,CAAC,EACvBD,EAAM,SAAS,EAAM,IAAU,CAE7B,IAAME,EAAQC,IAAU,EAAKC,EAAO,GAAQ,GAAOD,IAAU,EAAKC,EAAO,GAAQ,IAAOA,EACxFH,EAAI,KAAKC,EAAM,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAC9C,CAAC,EACD,IAAMG,EAAOJ,EAAI,KAAK,EAAE,EACxB,MAAO,CACLI,EAAK,MAAM,EAAG,CAAC,EACfA,EAAK,MAAM,EAAG,EAAE,EAChBA,EAAK,MAAM,GAAI,EAAE,EACjBA,EAAK,MAAM,GAAI,EAAE,EACjBA,EAAK,MAAM,EAAE,CACf,CAAC,CAAC,KAAK,GAAG,CACZ,CAQA,SAAgBC,EAAgB,EAAwB,CACtD,MAAO,GAAGb,IAASK,EAAa,GAClC"}
1
+ {"version":3,"file":"unique_key.js","names":["DEFAULT_UNIQUE_KEY_PREFIX","UNIQUE_KEY_PREFIX_PATTERN","resolveUniqueKeyPrefix","prefix","GalaSDKError","assertUniqueKey","isValidUniqueKey","uniqueKey","randomUuidV4","source","bytes","hex","value","index","byte","text","createUniqueKey"],"sources":["../../../src/utils/unique_key.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { isValidUniqueKey } from './unique_key_syntax.js';\n\n/**\n * The `uniqueKey` prefix the Gala Wallet and the gSwap web app have always sent\n * (`galaswap-operation-<uuid>`). The backend does not depend on it: the chain-write verifier\n * only requires a non-empty key of at most 256 characters, and apply-results accepts\n * `[A-Za-z0-9._:-]{1,128}`; the only code that mints a prefixed key itself is the server-side v1\n * trade builder, which nothing reads back by prefix.\n */\nexport const DEFAULT_UNIQUE_KEY_PREFIX = 'galaswap-operation-';\n\n/** Options shared by the services that mint `uniqueKey`s for writes. */\nexport interface UniqueKeyOptions {\n /**\n * Prefix of every minted `uniqueKey` (`<prefix><uuid>`). Defaults to\n * `DEFAULT_UNIQUE_KEY_PREFIX` (`galaswap-operation-`).\n */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/** A canonical UUID is 36 characters; the apply-results key limit is 128. */\nconst MAX_UNIQUE_KEY_PREFIX_LENGTH = 128 - 36;\nconst UNIQUE_KEY_PREFIX_PATTERN = /^[A-Za-z0-9._:-]*$/u;\n\n/**\n * Validates a caller-supplied `uniqueKey` prefix. The whole key (`<prefix><uuid>`) must stay a\n * valid apply-results key, otherwise `confirm()` could never read the outcome of the write.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY_PREFIX` when the prefix has characters outside\n * `A-Za-z0-9._:-` or is longer than 92 characters.\n */\nexport function resolveUniqueKeyPrefix(prefix: string | undefined): string {\n if (prefix === undefined) return DEFAULT_UNIQUE_KEY_PREFIX;\n if (!UNIQUE_KEY_PREFIX_PATTERN.test(prefix) || prefix.length > MAX_UNIQUE_KEY_PREFIX_LENGTH) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY_PREFIX', {\n uniqueKeyPrefix: prefix,\n maxLength: MAX_UNIQUE_KEY_PREFIX_LENGTH,\n });\n }\n return prefix;\n}\n\n/**\n * Validates a caller-supplied write `uniqueKey`: 1 to 128 characters of `A-Za-z0-9._:-`, the\n * shape the apply-results route accepts, so the write's outcome can always be read back with\n * `confirm()`. A key is one attempt's identity: reuse it only to retry that same attempt.\n *\n * @throws GalaSDKError `INVALID_UNIQUE_KEY` otherwise.\n */\nexport function assertUniqueKey(uniqueKey: string): void {\n if (!isValidUniqueKey(uniqueKey)) {\n throw new GalaSDKError('INVALID_UNIQUE_KEY', { uniqueKey: String(uniqueKey) });\n }\n}\n\n/** The part of `globalThis.crypto` a uniqueKey needs: the one CSPRNG every target can offer. */\ninterface RandomValuesSource {\n getRandomValues?: ((array: Uint8Array) => unknown) | undefined;\n}\n\n/**\n * A random version-4 UUID (RFC 9562) in the canonical lowercase `8-4-4-4-12` form, byte for byte\n * the shape `crypto.randomUUID()` returns, built from `crypto.getRandomValues`. `randomUUID` is\n * NOT used: React Native's Hermes has no `crypto.randomUUID`, so a write would fail with\n * \"undefined is not a function\", while `getRandomValues` is what browsers, Node (>= 19 as a\n * global), MV3 service workers and Hermes with `react-native-get-random-values` all provide.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when there is no `getRandomValues`: a key minted from\n * `Math.random` could collide with another attempt's, so the SDK refuses rather than degrade.\n */\nfunction randomUuidV4(): string {\n const source = (globalThis as { crypto?: RandomValuesSource | undefined }).crypto;\n if (typeof source?.getRandomValues !== 'function') {\n throw new GalaSDKError('CSPRNG_UNAVAILABLE', {});\n }\n // Filled in place: a polyfill is not relied on to return the array.\n const bytes = new Uint8Array(16);\n source.getRandomValues(bytes);\n const hex: string[] = [];\n bytes.forEach((byte, index) => {\n // Version nibble 4 in byte 6, variant bits 10 in byte 8; everything else stays random.\n const value = index === 6 ? (byte & 0x0f) | 0x40 : index === 8 ? (byte & 0x3f) | 0x80 : byte;\n hex.push(value.toString(16).padStart(2, '0'));\n });\n const text = hex.join('');\n return [\n text.slice(0, 8),\n text.slice(8, 12),\n text.slice(12, 16),\n text.slice(16, 20),\n text.slice(20),\n ].join('-');\n}\n\n/**\n * A fresh per-attempt key: `<prefix><random UUID>`, the UUID a random version-4 one.\n *\n * @throws GalaSDKError `CSPRNG_UNAVAILABLE` when the platform has no `crypto.getRandomValues`\n * (install a polyfill such as `react-native-get-random-values` on React Native).\n */\nexport function createUniqueKey(prefix: string): string {\n return `${prefix}${randomUuidV4()}`;\n}\n"],"mappings":"sHAUA,MAAaA,EAA4B,sBAanCC,EAA4B,sBASlC,SAAgBC,EAAuB,EAAoC,CACzE,GAAIC,IAAW,IAAA,GAAW,OAAOH,EACjC,GAAI,CAACC,EAA0B,KAAKE,CAAM,GAAKA,EAAO,OAAS,GAC7D,MAAM,IAAIC,EAAa,4BAA6B,CAClD,gBAAiBD,EACjB,UAAW,EACb,CAAC,EAEH,OAAOA,CACT,CASA,SAAgBE,EAAgB,EAAyB,CACvD,GAAI,CAACC,EAAiBC,CAAS,EAC7B,MAAM,IAAIH,EAAa,qBAAsB,CAAE,UAAW,OAAOG,CAAS,CAAE,CAAC,CAEjF,CAiBA,SAASC,GAAuB,CAC9B,IAAMC,EAAU,WAA2D,OAC3E,GAAI,OAAOA,GAAQ,iBAAoB,WACrC,MAAM,IAAIL,EAAa,qBAAsB,CAAC,CAAC,EAGjD,IAAMM,kBAAQ,IAAI,WAAW,EAAE,EAC/BD,EAAO,gBAAgBC,CAAK,EAC5B,IAAMC,EAAgB,CAAC,EACvBD,EAAM,SAAS,EAAM,IAAU,CAE7B,IAAME,EAAQC,IAAU,EAAKC,EAAO,GAAQ,GAAOD,IAAU,EAAKC,EAAO,GAAQ,IAAOA,EACxFH,EAAI,KAAKC,EAAM,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAC9C,CAAC,EACD,IAAMG,EAAOJ,EAAI,KAAK,EAAE,EACxB,MAAO,CACLI,EAAK,MAAM,EAAG,CAAC,EACfA,EAAK,MAAM,EAAG,EAAE,EAChBA,EAAK,MAAM,GAAI,EAAE,EACjBA,EAAK,MAAM,GAAI,EAAE,EACjBA,EAAK,MAAM,EAAE,CACf,CAAC,CAAC,KAAK,GAAG,CACZ,CAQA,SAAgBC,EAAgB,EAAwB,CACtD,MAAO,GAAGb,IAASK,EAAa,GAClC"}
@@ -1 +1 @@
1
- {"version":3,"file":"wallet_rejection.js","names":["REJECTION_CODES","REJECTION_PHRASES","TEXT_KEYS","isRecord","value","textsOf","depth","key","wordsADecline","lower","text","phrase","isWalletUserRejection","isGalaErrorLike","\"reason\"","hasGalaErrorBrand","\"code\"","\"name\"","walletDeclineCode","code"],"sources":["../../../src/utils/wallet_rejection.ts"],"sourcesContent":["/**\n * What the SDK knows about a failure thrown by a WALLET (the signer an app supplies, or wallet\n * code of the app's own): the code the wallet put on it, and whether it means the person declined.\n * Both read only the wallet's own error value; neither shows or forwards its text.\n */\n\nimport { hasGalaErrorBrand, isGalaErrorLike } from './error_brand.js';\n\n// This module is the whole of the light `@gala-chain/gala-core-sdk/wallet` entry (and the main\n// entry re-exports it, so there is one implementation). It must stay dependency-free: it may\n// import only `./error_brand.js`, never the error catalog, `GalaSDKError` or the main index.\n\n/** Codes the EIP-1193 / ethers / viem families use for \"the person declined in the wallet\". */\nconst REJECTION_CODES: readonly unknown[] = [4001, 'ACTION_REJECTED', 'USER_REJECTED'];\n\n/** The `name` viem / wagmi give the error of a declined request. */\nconst REJECTION_NAME = 'UserRejectedRequestError';\n\n/**\n * Wordings of a decline, matched case-insensitively as substrings. This is a LAST RESORT for\n * wallets that set neither a `code` nor a `name`: it reads a third party's text, so it is broad on\n * purpose (a superset of the matchers the Gala wallet and frontend_v2 used) and can in principle\n * match an unrelated message that uses these words.\n */\nconst REJECTION_PHRASES: readonly string[] = [\n 'user rejected',\n 'user denied',\n 'user cancel',\n 'rejected the request',\n 'request rejected',\n 'rejected by user',\n 'action_rejected',\n 'cancelled',\n 'canceled',\n];\n\n/** Properties wallets nest their text under (EIP-1193, ethers, viem, Gala wallet). */\nconst TEXT_KEYS: readonly string[] = [\n 'message',\n 'Message',\n 'shortMessage',\n 'details',\n 'errorDetails',\n 'reason',\n];\n\n/** Wallet errors nest their text at most a level or two deep; the bound also stops a cyclic object. */\nconst MAX_TEXT_DEPTH = 3;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction textsOf(value: unknown, depth = 0): string[] {\n if (typeof value === 'string') return [value];\n if (!isRecord(value) || depth >= MAX_TEXT_DEPTH) return [];\n return TEXT_KEYS.flatMap((key) => textsOf(value[key], depth + 1));\n}\n\nfunction wordsADecline(text: string): boolean {\n const lower = text.toLowerCase();\n return (\n REJECTION_PHRASES.some((phrase) => lower.includes(phrase)) ||\n (lower.includes('signature') && lower.includes('cancel'))\n );\n}\n\n/**\n * True when a wallet's error (or just its message text) says the person DECLINED the request in\n * their wallet. This is exactly the test behind `SIGNING_FAILED` with `params.reason ===\n * 'user_rejected'`, exported for wallet code outside the SDK (connect and registration flows, a\n * v1 write path) so an app keeps no matcher of its own.\n *\n * It is decided from the wallet's own fields first: a `code` of `4001` (EIP-1193), `'ACTION_REJECTED'`\n * (ethers) or `'USER_REJECTED'`, or `name === 'UserRejectedRequestError'` (viem). Only when those are\n * absent is the wallet's TEXT read (`message`, `Message`, `shortMessage`, `details`, `errorDetails`,\n * `reason`, up to three levels deep, or a bare string): \"user rejected\", \"user denied\", \"user\n * cancelled\", \"request rejected\", \"rejected by user\", \"rejected the request\", \"cancelled\" /\n * \"canceled\", or a \"signature ... cancel\" sentence. The wording fallback is a last resort for\n * wallets that do not set codes; prefer `code` and `name` wherever you control the wallet.\n *\n * An SDK error is never read by its text: a `SIGNING_FAILED` is a decline exactly when its\n * `params.reason` is `user_rejected`, and every other SDK error is not one. The same holds for a\n * plain-object VIEW of an SDK error (`{ code: 'SIGNING_FAILED', params: { reason } }`, the shape\n * of an app's wrapper): a string `code` plus an object `params` is decided by the code alone, with\n * the wallet code list above still honoured for a view that is not branded, and its English is\n * never read. This works without `instanceof`, so it is safe across two copies of the SDK.\n *\n * @example\n * ```ts\n * try {\n * await wallet.connect();\n * } catch (error) {\n * if (isWalletUserRejection(error)) return; // the person said no: not an error to report\n * report(error);\n * }\n * ```\n */\nexport function isWalletUserRejection(value: unknown): boolean {\n if (isGalaErrorLike(value)) {\n if (value.code === 'SIGNING_FAILED') return value.params['reason'] === 'user_rejected';\n return !hasGalaErrorBrand(value) && REJECTION_CODES.includes(value.code);\n }\n if (isRecord(value)) {\n if (REJECTION_CODES.includes(value['code']) || value['name'] === REJECTION_NAME) return true;\n }\n return textsOf(value).some(wordsADecline);\n}\n\n/** The longest wallet code kept: real ones (`4001`, `ACTION_REJECTED`) are short. */\nconst MAX_WALLET_CODE_LENGTH = 64;\n\n/**\n * The code a wallet put on its error: an EIP-1193 / JSON-RPC number (`4001`, `-32603`) or an\n * ethers / viem string (`'ACTION_REJECTED'`), read from the error's own top-level `code`. Anything\n * else (no code, a non-finite number, an empty or very long string, an object) is `undefined`, so\n * the value is always a safe primitive. Used for `GalaSDKError.walletCode`.\n *\n * @example\n * ```ts\n * walletDeclineCode({ code: 4001, message: 'User rejected the request.' }); // 4001\n * walletDeclineCode(new Error('locked')); // undefined\n * ```\n */\nexport function walletDeclineCode(value: unknown): number | string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { code } = value as { code?: unknown };\n if (typeof code === 'number') return Number.isFinite(code) ? code : undefined;\n if (typeof code === 'string' && code.length > 0 && code.length <= MAX_WALLET_CODE_LENGTH) {\n return code;\n }\n return undefined;\n}\n"],"mappings":"0EAaA,MAAMA,EAAsC,CAAC,KAAM,kBAAmB,eAAe,EAW/EC,EAAuC,CAC3C,gBACA,cACA,cACA,uBACA,mBACA,mBACA,kBACA,YACA,UACF,EAGMC,EAA+B,CACnC,UACA,UACA,eACA,UACA,eACA,QACF,EAKA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAEA,SAASC,EAAQ,EAAgB,EAAQ,EAAa,CAGpD,OAFI,OAAOD,GAAU,SAAiB,CAACA,CAAK,EACxC,CAACD,EAASC,CAAK,GAAKE,GAAS,EAAuB,CAAC,EAClDJ,EAAU,QAAS,GAAQG,EAAQD,EAAMG,GAAMD,EAAQ,CAAC,CAAC,CAClE,CAEA,SAASE,EAAc,EAAuB,CAC5C,IAAMC,EAAQC,EAAK,YAAY,EAC/B,OACET,EAAkB,KAAM,GAAWQ,EAAM,SAASE,CAAM,CAAC,GACxDF,EAAM,SAAS,WAAW,GAAKA,EAAM,SAAS,QAAQ,CAE3D,CAiCA,SAAgBG,EAAsB,EAAyB,CAQ7D,OAPIC,EAAgBT,CAAK,EACnBA,EAAM,OAAS,iBAAyBA,EAAM,OAAOU,SAAc,gBAChE,CAACC,EAAkBX,CAAK,GAAKJ,EAAgB,SAASI,EAAM,IAAI,EAErED,EAASC,CAAK,IACZJ,EAAgB,SAASI,EAAMY,IAAO,GAAKZ,EAAMa,OAAY,4BAAuB,GAEnFZ,EAAQD,CAAK,CAAC,CAAC,KAAKI,CAAa,CAC1C,CAiBA,SAAgBU,EAAkB,EAA6C,CAC7E,GAAI,OAAOd,GAAU,WAAYA,EAAgB,OACjD,GAAM,CAAE,QAASA,EACjB,GAAI,OAAOe,GAAS,SAAU,OAAO,OAAO,SAASA,CAAI,EAAIA,EAAO,IAAA,GACpE,GAAI,OAAOA,GAAS,UAAYA,EAAK,OAAS,GAAKA,EAAK,QAAU,GAChE,OAAOA,CAGX"}
1
+ {"version":3,"file":"wallet_rejection.js","names":["REJECTION_CODES","REJECTION_PHRASES","TEXT_KEYS","isRecord","value","textsOf","depth","key","wordsADecline","lower","text","phrase","isWalletUserRejection","isGalaErrorLike","\"reason\"","hasGalaErrorBrand","\"code\"","\"name\"","walletDeclineCode","code"],"sources":["../../../src/utils/wallet_rejection.ts"],"sourcesContent":["/**\n * What the SDK knows about a failure thrown by a WALLET (the signer an app supplies, or wallet\n * code of the app's own): the code the wallet put on it, and whether it means the person declined.\n * Both read only the wallet's own error value; neither shows or forwards its text.\n */\n\nimport { hasGalaErrorBrand, isGalaErrorLike } from './error_brand.js';\n\n// This module is the whole of the light `@gala-chain/gala-core-sdk/wallet` entry (and the main\n// entry re-exports it, so there is one implementation). It must stay dependency-free: it may\n// import only `./error_brand.js`, never the error catalog, `GalaSDKError` or the main index.\n\n/** Codes the EIP-1193 / ethers / viem families use for \"the person declined in the wallet\". */\nconst REJECTION_CODES: readonly unknown[] = [4001, 'ACTION_REJECTED', 'USER_REJECTED'];\n\n/** The `name` viem / wagmi give the error of a declined request. */\nconst REJECTION_NAME = 'UserRejectedRequestError';\n\n/**\n * Wordings of a decline, matched case-insensitively as substrings. This is a LAST RESORT for\n * wallets that set neither a `code` nor a `name`: it reads a third party's text, so it is broad on\n * purpose (a superset of the matchers the Gala wallet and gSwap web app used) and can in principle\n * match an unrelated message that uses these words.\n */\nconst REJECTION_PHRASES: readonly string[] = [\n 'user rejected',\n 'user denied',\n 'user cancel',\n 'rejected the request',\n 'request rejected',\n 'rejected by user',\n 'action_rejected',\n 'cancelled',\n 'canceled',\n];\n\n/** Properties wallets nest their text under (EIP-1193, ethers, viem, Gala wallet). */\nconst TEXT_KEYS: readonly string[] = [\n 'message',\n 'Message',\n 'shortMessage',\n 'details',\n 'errorDetails',\n 'reason',\n];\n\n/** Wallet errors nest their text at most a level or two deep; the bound also stops a cyclic object. */\nconst MAX_TEXT_DEPTH = 3;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction textsOf(value: unknown, depth = 0): string[] {\n if (typeof value === 'string') return [value];\n if (!isRecord(value) || depth >= MAX_TEXT_DEPTH) return [];\n return TEXT_KEYS.flatMap((key) => textsOf(value[key], depth + 1));\n}\n\nfunction wordsADecline(text: string): boolean {\n const lower = text.toLowerCase();\n return (\n REJECTION_PHRASES.some((phrase) => lower.includes(phrase)) ||\n (lower.includes('signature') && lower.includes('cancel'))\n );\n}\n\n/**\n * True when a wallet's error (or just its message text) says the person DECLINED the request in\n * their wallet. This is exactly the test behind `SIGNING_FAILED` with `params.reason ===\n * 'user_rejected'`, exported for wallet code outside the SDK (connect and registration flows, a\n * v1 write path) so an app keeps no matcher of its own.\n *\n * It is decided from the wallet's own fields first: a `code` of `4001` (EIP-1193), `'ACTION_REJECTED'`\n * (ethers) or `'USER_REJECTED'`, or `name === 'UserRejectedRequestError'` (viem). Only when those are\n * absent is the wallet's TEXT read (`message`, `Message`, `shortMessage`, `details`, `errorDetails`,\n * `reason`, up to three levels deep, or a bare string): \"user rejected\", \"user denied\", \"user\n * cancelled\", \"request rejected\", \"rejected by user\", \"rejected the request\", \"cancelled\" /\n * \"canceled\", or a \"signature ... cancel\" sentence. The wording fallback is a last resort for\n * wallets that do not set codes; prefer `code` and `name` wherever you control the wallet.\n *\n * An SDK error is never read by its text: a `SIGNING_FAILED` is a decline exactly when its\n * `params.reason` is `user_rejected`, and every other SDK error is not one. The same holds for a\n * plain-object VIEW of an SDK error (`{ code: 'SIGNING_FAILED', params: { reason } }`, the shape\n * of an app's wrapper): a string `code` plus an object `params` is decided by the code alone, with\n * the wallet code list above still honoured for a view that is not branded, and its English is\n * never read. This works without `instanceof`, so it is safe across two copies of the SDK.\n *\n * @example\n * ```ts\n * try {\n * await wallet.connect();\n * } catch (error) {\n * if (isWalletUserRejection(error)) return; // the person said no: not an error to report\n * report(error);\n * }\n * ```\n */\nexport function isWalletUserRejection(value: unknown): boolean {\n if (isGalaErrorLike(value)) {\n if (value.code === 'SIGNING_FAILED') return value.params['reason'] === 'user_rejected';\n return !hasGalaErrorBrand(value) && REJECTION_CODES.includes(value.code);\n }\n if (isRecord(value)) {\n if (REJECTION_CODES.includes(value['code']) || value['name'] === REJECTION_NAME) return true;\n }\n return textsOf(value).some(wordsADecline);\n}\n\n/** The longest wallet code kept: real ones (`4001`, `ACTION_REJECTED`) are short. */\nconst MAX_WALLET_CODE_LENGTH = 64;\n\n/**\n * The code a wallet put on its error: an EIP-1193 / JSON-RPC number (`4001`, `-32603`) or an\n * ethers / viem string (`'ACTION_REJECTED'`), read from the error's own top-level `code`. Anything\n * else (no code, a non-finite number, an empty or very long string, an object) is `undefined`, so\n * the value is always a safe primitive. Used for `GalaSDKError.walletCode`.\n *\n * @example\n * ```ts\n * walletDeclineCode({ code: 4001, message: 'User rejected the request.' }); // 4001\n * walletDeclineCode(new Error('locked')); // undefined\n * ```\n */\nexport function walletDeclineCode(value: unknown): number | string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { code } = value as { code?: unknown };\n if (typeof code === 'number') return Number.isFinite(code) ? code : undefined;\n if (typeof code === 'string' && code.length > 0 && code.length <= MAX_WALLET_CODE_LENGTH) {\n return code;\n }\n return undefined;\n}\n"],"mappings":"0EAaA,MAAMA,EAAsC,CAAC,KAAM,kBAAmB,eAAe,EAW/EC,EAAuC,CAC3C,gBACA,cACA,cACA,uBACA,mBACA,mBACA,kBACA,YACA,UACF,EAGMC,EAA+B,CACnC,UACA,UACA,eACA,UACA,eACA,QACF,EAKA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,CACtC,CAEA,SAASC,EAAQ,EAAgB,EAAQ,EAAa,CAGpD,OAFI,OAAOD,GAAU,SAAiB,CAACA,CAAK,EACxC,CAACD,EAASC,CAAK,GAAKE,GAAS,EAAuB,CAAC,EAClDJ,EAAU,QAAS,GAAQG,EAAQD,EAAMG,GAAMD,EAAQ,CAAC,CAAC,CAClE,CAEA,SAASE,EAAc,EAAuB,CAC5C,IAAMC,EAAQC,EAAK,YAAY,EAC/B,OACET,EAAkB,KAAM,GAAWQ,EAAM,SAASE,CAAM,CAAC,GACxDF,EAAM,SAAS,WAAW,GAAKA,EAAM,SAAS,QAAQ,CAE3D,CAiCA,SAAgBG,EAAsB,EAAyB,CAQ7D,OAPIC,EAAgBT,CAAK,EACnBA,EAAM,OAAS,iBAAyBA,EAAM,OAAOU,SAAc,gBAChE,CAACC,EAAkBX,CAAK,GAAKJ,EAAgB,SAASI,EAAM,IAAI,EAErED,EAASC,CAAK,IACZJ,EAAgB,SAASI,EAAMY,IAAO,GAAKZ,EAAMa,OAAY,4BAAuB,GAEnFZ,EAAQD,CAAK,CAAC,CAAC,KAAKI,CAAa,CAC1C,CAiBA,SAAgBU,EAAkB,EAA6C,CAC7E,GAAI,OAAOd,GAAU,WAAYA,EAAgB,OACjD,GAAM,CAAE,QAASA,EACjB,GAAI,OAAOe,GAAS,SAAU,OAAO,OAAO,SAASA,CAAI,EAAIA,EAAO,IAAA,GACpE,GAAI,OAAOA,GAAS,UAAYA,EAAK,OAAS,GAAKA,EAAK,QAAU,GAChE,OAAOA,CAGX"}
@@ -1,2 +1,2 @@
1
- const e=`1.0.0-rc.7`;export{e as GALA_CORE_SDK_VERSION};
1
+ const e=`1.0.0`;export{e as GALA_CORE_SDK_VERSION};
2
2
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":["GALA_CORE_SDK_VERSION"],"sources":["../../src/version.ts"],"sourcesContent":["declare const __GALA_CORE_SDK_VERSION__: string | undefined;\n\n/**\n * The `@gala-chain/gala-core-sdk` package version, embedded by the bundler, with a source-test\n * fallback. It is the version in the default `User-Agent` (`GalaChain-SDK/<version>`) of every SDK\n * request, whichever product SDK sends it.\n */\nexport const GALA_CORE_SDK_VERSION =\n typeof __GALA_CORE_SDK_VERSION__ === 'string' ? __GALA_CORE_SDK_VERSION__ : '1.0.0-rc.7';\n"],"mappings":"AAOA,MAAaA,EAAA"}
1
+ {"version":3,"file":"version.js","names":["GALA_CORE_SDK_VERSION"],"sources":["../../src/version.ts"],"sourcesContent":["declare const __GALA_CORE_SDK_VERSION__: string | undefined;\n\n/**\n * The `@gala-chain/gala-core-sdk` package version, embedded by the bundler, with a source-test\n * fallback. It is the version in the default `User-Agent` (`GalaChain-SDK/<version>`) of every SDK\n * request, whichever product SDK sends it.\n */\nexport const GALA_CORE_SDK_VERSION =\n typeof __GALA_CORE_SDK_VERSION__ === 'string' ? __GALA_CORE_SDK_VERSION__ : '1.0.0';\n"],"mappings":"AAOA,MAAaA,EAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"wallet.js","names":["isRecord","GALA_ERROR_BRAND","isRecord$1","value","hasGalaErrorBrand","isGalaErrorLike","\"code\"","\"params\"","REJECTION_CODES","REJECTION_PHRASES","TEXT_KEYS","isRecord","textsOf","depth","key","wordsADecline","lower","text","phrase","isWalletUserRejection","\"reason\"","\"name\"","walletDeclineCode","code"],"sources":["../../src/utils/error_brand.ts","../../src/utils/wallet_rejection.ts"],"sourcesContent":["/**\n * The brand every `GalaSDKError` (and so every product SDK's error) carries, and the duck-type\n * check for the \"failure shape\". This module has NO imports on purpose: it is part of the light\n * `@gala-chain/gala-core-sdk/wallet` entry, which must never pull the error catalog or the main\n * bundle in.\n */\n\n/**\n * The brand of an SDK error: `error[GALA_ERROR_BRAND] === true`. It is a registered symbol\n * (`Symbol.for`), so two copies of the SDK in one page (a wallet bundle and an app bundle) still\n * recognise each other's errors, which `instanceof` cannot do.\n */\nexport const GALA_ERROR_BRAND: unique symbol = Symbol.for('@gala-chain/gala-core-sdk/error');\n\n/** The least an object must have to be read as an SDK error or its plain-object view. */\nexport interface GalaErrorShape {\n readonly code: string;\n readonly params: Readonly<Record<string, unknown>>;\n}\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** True when `value` carries the SDK error brand (a real `GalaSDKError`, from any copy of the SDK). */\nexport function hasGalaErrorBrand(value: unknown): boolean {\n return isRecord(value) && value[GALA_ERROR_BRAND] === true;\n}\n\n/**\n * True when `value` is an SDK error (it carries the brand) or a plain-object VIEW of one: a string\n * `code` and an object `params`, which is the shape of `GalaSDKError` and of the wrapper objects\n * an app builds from one (`{ code, params, status?, phase?, ... }`). A wallet's own error (an\n * EIP-1193 numeric `code`, an ethers error with a string `code` and no `params`) is neither. It\n * says the value has the SDK's shape, not that `code` is a code the SDK knows.\n *\n * @example\n * ```ts\n * if (isGalaErrorLike(error)) report(error.code, error.params); // no `instanceof`, no SDK import\n * ```\n */\nexport function isGalaErrorLike(value: unknown): value is GalaErrorShape {\n if (hasGalaErrorBrand(value)) return true;\n return (\n isRecord(value) &&\n typeof value['code'] === 'string' &&\n isRecord(value['params']) &&\n !Array.isArray(value['params'])\n );\n}\n","/**\n * What the SDK knows about a failure thrown by a WALLET (the signer an app supplies, or wallet\n * code of the app's own): the code the wallet put on it, and whether it means the person declined.\n * Both read only the wallet's own error value; neither shows or forwards its text.\n */\n\nimport { hasGalaErrorBrand, isGalaErrorLike } from './error_brand.js';\n\n// This module is the whole of the light `@gala-chain/gala-core-sdk/wallet` entry (and the main\n// entry re-exports it, so there is one implementation). It must stay dependency-free: it may\n// import only `./error_brand.js`, never the error catalog, `GalaSDKError` or the main index.\n\n/** Codes the EIP-1193 / ethers / viem families use for \"the person declined in the wallet\". */\nconst REJECTION_CODES: readonly unknown[] = [4001, 'ACTION_REJECTED', 'USER_REJECTED'];\n\n/** The `name` viem / wagmi give the error of a declined request. */\nconst REJECTION_NAME = 'UserRejectedRequestError';\n\n/**\n * Wordings of a decline, matched case-insensitively as substrings. This is a LAST RESORT for\n * wallets that set neither a `code` nor a `name`: it reads a third party's text, so it is broad on\n * purpose (a superset of the matchers the Gala wallet and frontend_v2 used) and can in principle\n * match an unrelated message that uses these words.\n */\nconst REJECTION_PHRASES: readonly string[] = [\n 'user rejected',\n 'user denied',\n 'user cancel',\n 'rejected the request',\n 'request rejected',\n 'rejected by user',\n 'action_rejected',\n 'cancelled',\n 'canceled',\n];\n\n/** Properties wallets nest their text under (EIP-1193, ethers, viem, Gala wallet). */\nconst TEXT_KEYS: readonly string[] = [\n 'message',\n 'Message',\n 'shortMessage',\n 'details',\n 'errorDetails',\n 'reason',\n];\n\n/** Wallet errors nest their text at most a level or two deep; the bound also stops a cyclic object. */\nconst MAX_TEXT_DEPTH = 3;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction textsOf(value: unknown, depth = 0): string[] {\n if (typeof value === 'string') return [value];\n if (!isRecord(value) || depth >= MAX_TEXT_DEPTH) return [];\n return TEXT_KEYS.flatMap((key) => textsOf(value[key], depth + 1));\n}\n\nfunction wordsADecline(text: string): boolean {\n const lower = text.toLowerCase();\n return (\n REJECTION_PHRASES.some((phrase) => lower.includes(phrase)) ||\n (lower.includes('signature') && lower.includes('cancel'))\n );\n}\n\n/**\n * True when a wallet's error (or just its message text) says the person DECLINED the request in\n * their wallet. This is exactly the test behind `SIGNING_FAILED` with `params.reason ===\n * 'user_rejected'`, exported for wallet code outside the SDK (connect and registration flows, a\n * v1 write path) so an app keeps no matcher of its own.\n *\n * It is decided from the wallet's own fields first: a `code` of `4001` (EIP-1193), `'ACTION_REJECTED'`\n * (ethers) or `'USER_REJECTED'`, or `name === 'UserRejectedRequestError'` (viem). Only when those are\n * absent is the wallet's TEXT read (`message`, `Message`, `shortMessage`, `details`, `errorDetails`,\n * `reason`, up to three levels deep, or a bare string): \"user rejected\", \"user denied\", \"user\n * cancelled\", \"request rejected\", \"rejected by user\", \"rejected the request\", \"cancelled\" /\n * \"canceled\", or a \"signature ... cancel\" sentence. The wording fallback is a last resort for\n * wallets that do not set codes; prefer `code` and `name` wherever you control the wallet.\n *\n * An SDK error is never read by its text: a `SIGNING_FAILED` is a decline exactly when its\n * `params.reason` is `user_rejected`, and every other SDK error is not one. The same holds for a\n * plain-object VIEW of an SDK error (`{ code: 'SIGNING_FAILED', params: { reason } }`, the shape\n * of an app's wrapper): a string `code` plus an object `params` is decided by the code alone, with\n * the wallet code list above still honoured for a view that is not branded, and its English is\n * never read. This works without `instanceof`, so it is safe across two copies of the SDK.\n *\n * @example\n * ```ts\n * try {\n * await wallet.connect();\n * } catch (error) {\n * if (isWalletUserRejection(error)) return; // the person said no: not an error to report\n * report(error);\n * }\n * ```\n */\nexport function isWalletUserRejection(value: unknown): boolean {\n if (isGalaErrorLike(value)) {\n if (value.code === 'SIGNING_FAILED') return value.params['reason'] === 'user_rejected';\n return !hasGalaErrorBrand(value) && REJECTION_CODES.includes(value.code);\n }\n if (isRecord(value)) {\n if (REJECTION_CODES.includes(value['code']) || value['name'] === REJECTION_NAME) return true;\n }\n return textsOf(value).some(wordsADecline);\n}\n\n/** The longest wallet code kept: real ones (`4001`, `ACTION_REJECTED`) are short. */\nconst MAX_WALLET_CODE_LENGTH = 64;\n\n/**\n * The code a wallet put on its error: an EIP-1193 / JSON-RPC number (`4001`, `-32603`) or an\n * ethers / viem string (`'ACTION_REJECTED'`), read from the error's own top-level `code`. Anything\n * else (no code, a non-finite number, an empty or very long string, an object) is `undefined`, so\n * the value is always a safe primitive. Used for `GalaSDKError.walletCode`.\n *\n * @example\n * ```ts\n * walletDeclineCode({ code: 4001, message: 'User rejected the request.' }); // 4001\n * walletDeclineCode(new Error('locked')); // undefined\n * ```\n */\nexport function walletDeclineCode(value: unknown): number | string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { code } = value as { code?: unknown };\n if (typeof code === 'number') return Number.isFinite(code) ? code : undefined;\n if (typeof code === 'string' && code.length > 0 && code.length <= MAX_WALLET_CODE_LENGTH) {\n return code;\n }\n return undefined;\n}\n"],"mappings":"AAYA,MAAaC,EAAkC,OAAO,IAAI,iCAAiC,EAQ3F,SAASD,EAAS,EAAuD,CACvE,OAAO,OAAOG,GAAU,YAAYA,CACtC,CAGA,SAAgBC,EAAkB,EAAyB,CACzD,OAAOJ,EAASG,CAAK,GAAKA,EAAMF,KAAsB,EACxD,CAcA,SAAgBI,EAAgB,EAAyC,CAEvE,OADID,EAAkBD,CAAK,EAAU,GAEnCH,EAASG,CAAK,GACd,OAAOA,EAAMG,MAAY,UACzBN,EAASG,EAAMI,MAAS,GACxB,CAAC,MAAM,QAAQJ,EAAMI,MAAS,CAElC,CCpCA,MAAMC,EAAsC,CAAC,KAAM,kBAAmB,eAAe,EAW/EC,EAAuC,CAC3C,gBACA,cACA,cACA,uBACA,mBACA,mBACA,kBACA,YACA,UACF,EAGMC,EAA+B,CACnC,UACA,UACA,eACA,UACA,eACA,QACF,EAKA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOR,GAAU,YAAYA,CACtC,CAEA,SAASS,EAAQ,EAAgB,EAAQ,EAAa,CAGpD,OAFI,OAAOT,GAAU,SAAiB,CAACA,CAAK,EACxC,CAACQ,EAASR,CAAK,GAAKU,GAAS,EAAuB,CAAC,EAClDH,EAAU,QAAS,GAAQE,EAAQT,EAAMW,GAAMD,EAAQ,CAAC,CAAC,CAClE,CAEA,SAASE,EAAc,EAAuB,CAC5C,IAAMC,EAAQC,EAAK,YAAY,EAC/B,OACER,EAAkB,KAAM,GAAWO,EAAM,SAASE,CAAM,CAAC,GACxDF,EAAM,SAAS,WAAW,GAAKA,EAAM,SAAS,QAAQ,CAE3D,CAiCA,SAAgBG,EAAsB,EAAyB,CAQ7D,OAPId,EAAgBF,CAAK,EACnBA,EAAM,OAAS,iBAAyBA,EAAM,OAAOiB,SAAc,gBAChE,CAAChB,EAAkBD,CAAK,GAAKK,EAAgB,SAASL,EAAM,IAAI,EAErEQ,EAASR,CAAK,IACZK,EAAgB,SAASL,EAAMG,IAAO,GAAKH,EAAMkB,OAAY,4BAAuB,GAEnFT,EAAQT,CAAK,CAAC,CAAC,KAAKY,CAAa,CAC1C,CAiBA,SAAgBO,EAAkB,EAA6C,CAC7E,GAAI,OAAOnB,GAAU,WAAYA,EAAgB,OACjD,GAAM,CAAE,QAASA,EACjB,GAAI,OAAOoB,GAAS,SAAU,OAAO,OAAO,SAASA,CAAI,EAAIA,EAAO,IAAA,GACpE,GAAI,OAAOA,GAAS,UAAYA,EAAK,OAAS,GAAKA,EAAK,QAAU,GAChE,OAAOA,CAGX"}
1
+ {"version":3,"file":"wallet.js","names":["isRecord","GALA_ERROR_BRAND","isRecord$1","value","hasGalaErrorBrand","isGalaErrorLike","\"code\"","\"params\"","REJECTION_CODES","REJECTION_PHRASES","TEXT_KEYS","isRecord","textsOf","depth","key","wordsADecline","lower","text","phrase","isWalletUserRejection","\"reason\"","\"name\"","walletDeclineCode","code"],"sources":["../../src/utils/error_brand.ts","../../src/utils/wallet_rejection.ts"],"sourcesContent":["/**\n * The brand every `GalaSDKError` (and so every product SDK's error) carries, and the duck-type\n * check for the \"failure shape\". This module has NO imports on purpose: it is part of the light\n * `@gala-chain/gala-core-sdk/wallet` entry, which must never pull the error catalog or the main\n * bundle in.\n */\n\n/**\n * The brand of an SDK error: `error[GALA_ERROR_BRAND] === true`. It is a registered symbol\n * (`Symbol.for`), so two copies of the SDK in one page (a wallet bundle and an app bundle) still\n * recognise each other's errors, which `instanceof` cannot do.\n */\nexport const GALA_ERROR_BRAND: unique symbol = Symbol.for('@gala-chain/gala-core-sdk/error');\n\n/** The least an object must have to be read as an SDK error or its plain-object view. */\nexport interface GalaErrorShape {\n readonly code: string;\n readonly params: Readonly<Record<string, unknown>>;\n}\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** True when `value` carries the SDK error brand (a real `GalaSDKError`, from any copy of the SDK). */\nexport function hasGalaErrorBrand(value: unknown): boolean {\n return isRecord(value) && value[GALA_ERROR_BRAND] === true;\n}\n\n/**\n * True when `value` is an SDK error (it carries the brand) or a plain-object VIEW of one: a string\n * `code` and an object `params`, which is the shape of `GalaSDKError` and of the wrapper objects\n * an app builds from one (`{ code, params, status?, phase?, ... }`). A wallet's own error (an\n * EIP-1193 numeric `code`, an ethers error with a string `code` and no `params`) is neither. It\n * says the value has the SDK's shape, not that `code` is a code the SDK knows.\n *\n * @example\n * ```ts\n * if (isGalaErrorLike(error)) report(error.code, error.params); // no `instanceof`, no SDK import\n * ```\n */\nexport function isGalaErrorLike(value: unknown): value is GalaErrorShape {\n if (hasGalaErrorBrand(value)) return true;\n return (\n isRecord(value) &&\n typeof value['code'] === 'string' &&\n isRecord(value['params']) &&\n !Array.isArray(value['params'])\n );\n}\n","/**\n * What the SDK knows about a failure thrown by a WALLET (the signer an app supplies, or wallet\n * code of the app's own): the code the wallet put on it, and whether it means the person declined.\n * Both read only the wallet's own error value; neither shows or forwards its text.\n */\n\nimport { hasGalaErrorBrand, isGalaErrorLike } from './error_brand.js';\n\n// This module is the whole of the light `@gala-chain/gala-core-sdk/wallet` entry (and the main\n// entry re-exports it, so there is one implementation). It must stay dependency-free: it may\n// import only `./error_brand.js`, never the error catalog, `GalaSDKError` or the main index.\n\n/** Codes the EIP-1193 / ethers / viem families use for \"the person declined in the wallet\". */\nconst REJECTION_CODES: readonly unknown[] = [4001, 'ACTION_REJECTED', 'USER_REJECTED'];\n\n/** The `name` viem / wagmi give the error of a declined request. */\nconst REJECTION_NAME = 'UserRejectedRequestError';\n\n/**\n * Wordings of a decline, matched case-insensitively as substrings. This is a LAST RESORT for\n * wallets that set neither a `code` nor a `name`: it reads a third party's text, so it is broad on\n * purpose (a superset of the matchers the Gala wallet and gSwap web app used) and can in principle\n * match an unrelated message that uses these words.\n */\nconst REJECTION_PHRASES: readonly string[] = [\n 'user rejected',\n 'user denied',\n 'user cancel',\n 'rejected the request',\n 'request rejected',\n 'rejected by user',\n 'action_rejected',\n 'cancelled',\n 'canceled',\n];\n\n/** Properties wallets nest their text under (EIP-1193, ethers, viem, Gala wallet). */\nconst TEXT_KEYS: readonly string[] = [\n 'message',\n 'Message',\n 'shortMessage',\n 'details',\n 'errorDetails',\n 'reason',\n];\n\n/** Wallet errors nest their text at most a level or two deep; the bound also stops a cyclic object. */\nconst MAX_TEXT_DEPTH = 3;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction textsOf(value: unknown, depth = 0): string[] {\n if (typeof value === 'string') return [value];\n if (!isRecord(value) || depth >= MAX_TEXT_DEPTH) return [];\n return TEXT_KEYS.flatMap((key) => textsOf(value[key], depth + 1));\n}\n\nfunction wordsADecline(text: string): boolean {\n const lower = text.toLowerCase();\n return (\n REJECTION_PHRASES.some((phrase) => lower.includes(phrase)) ||\n (lower.includes('signature') && lower.includes('cancel'))\n );\n}\n\n/**\n * True when a wallet's error (or just its message text) says the person DECLINED the request in\n * their wallet. This is exactly the test behind `SIGNING_FAILED` with `params.reason ===\n * 'user_rejected'`, exported for wallet code outside the SDK (connect and registration flows, a\n * v1 write path) so an app keeps no matcher of its own.\n *\n * It is decided from the wallet's own fields first: a `code` of `4001` (EIP-1193), `'ACTION_REJECTED'`\n * (ethers) or `'USER_REJECTED'`, or `name === 'UserRejectedRequestError'` (viem). Only when those are\n * absent is the wallet's TEXT read (`message`, `Message`, `shortMessage`, `details`, `errorDetails`,\n * `reason`, up to three levels deep, or a bare string): \"user rejected\", \"user denied\", \"user\n * cancelled\", \"request rejected\", \"rejected by user\", \"rejected the request\", \"cancelled\" /\n * \"canceled\", or a \"signature ... cancel\" sentence. The wording fallback is a last resort for\n * wallets that do not set codes; prefer `code` and `name` wherever you control the wallet.\n *\n * An SDK error is never read by its text: a `SIGNING_FAILED` is a decline exactly when its\n * `params.reason` is `user_rejected`, and every other SDK error is not one. The same holds for a\n * plain-object VIEW of an SDK error (`{ code: 'SIGNING_FAILED', params: { reason } }`, the shape\n * of an app's wrapper): a string `code` plus an object `params` is decided by the code alone, with\n * the wallet code list above still honoured for a view that is not branded, and its English is\n * never read. This works without `instanceof`, so it is safe across two copies of the SDK.\n *\n * @example\n * ```ts\n * try {\n * await wallet.connect();\n * } catch (error) {\n * if (isWalletUserRejection(error)) return; // the person said no: not an error to report\n * report(error);\n * }\n * ```\n */\nexport function isWalletUserRejection(value: unknown): boolean {\n if (isGalaErrorLike(value)) {\n if (value.code === 'SIGNING_FAILED') return value.params['reason'] === 'user_rejected';\n return !hasGalaErrorBrand(value) && REJECTION_CODES.includes(value.code);\n }\n if (isRecord(value)) {\n if (REJECTION_CODES.includes(value['code']) || value['name'] === REJECTION_NAME) return true;\n }\n return textsOf(value).some(wordsADecline);\n}\n\n/** The longest wallet code kept: real ones (`4001`, `ACTION_REJECTED`) are short. */\nconst MAX_WALLET_CODE_LENGTH = 64;\n\n/**\n * The code a wallet put on its error: an EIP-1193 / JSON-RPC number (`4001`, `-32603`) or an\n * ethers / viem string (`'ACTION_REJECTED'`), read from the error's own top-level `code`. Anything\n * else (no code, a non-finite number, an empty or very long string, an object) is `undefined`, so\n * the value is always a safe primitive. Used for `GalaSDKError.walletCode`.\n *\n * @example\n * ```ts\n * walletDeclineCode({ code: 4001, message: 'User rejected the request.' }); // 4001\n * walletDeclineCode(new Error('locked')); // undefined\n * ```\n */\nexport function walletDeclineCode(value: unknown): number | string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { code } = value as { code?: unknown };\n if (typeof code === 'number') return Number.isFinite(code) ? code : undefined;\n if (typeof code === 'string' && code.length > 0 && code.length <= MAX_WALLET_CODE_LENGTH) {\n return code;\n }\n return undefined;\n}\n"],"mappings":"AAYA,MAAaC,EAAkC,OAAO,IAAI,iCAAiC,EAQ3F,SAASD,EAAS,EAAuD,CACvE,OAAO,OAAOG,GAAU,YAAYA,CACtC,CAGA,SAAgBC,EAAkB,EAAyB,CACzD,OAAOJ,EAASG,CAAK,GAAKA,EAAMF,KAAsB,EACxD,CAcA,SAAgBI,EAAgB,EAAyC,CAEvE,OADID,EAAkBD,CAAK,EAAU,GAEnCH,EAASG,CAAK,GACd,OAAOA,EAAMG,MAAY,UACzBN,EAASG,EAAMI,MAAS,GACxB,CAAC,MAAM,QAAQJ,EAAMI,MAAS,CAElC,CCpCA,MAAMC,EAAsC,CAAC,KAAM,kBAAmB,eAAe,EAW/EC,EAAuC,CAC3C,gBACA,cACA,cACA,uBACA,mBACA,mBACA,kBACA,YACA,UACF,EAGMC,EAA+B,CACnC,UACA,UACA,eACA,UACA,eACA,QACF,EAKA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOR,GAAU,YAAYA,CACtC,CAEA,SAASS,EAAQ,EAAgB,EAAQ,EAAa,CAGpD,OAFI,OAAOT,GAAU,SAAiB,CAACA,CAAK,EACxC,CAACQ,EAASR,CAAK,GAAKU,GAAS,EAAuB,CAAC,EAClDH,EAAU,QAAS,GAAQE,EAAQT,EAAMW,GAAMD,EAAQ,CAAC,CAAC,CAClE,CAEA,SAASE,EAAc,EAAuB,CAC5C,IAAMC,EAAQC,EAAK,YAAY,EAC/B,OACER,EAAkB,KAAM,GAAWO,EAAM,SAASE,CAAM,CAAC,GACxDF,EAAM,SAAS,WAAW,GAAKA,EAAM,SAAS,QAAQ,CAE3D,CAiCA,SAAgBG,EAAsB,EAAyB,CAQ7D,OAPId,EAAgBF,CAAK,EACnBA,EAAM,OAAS,iBAAyBA,EAAM,OAAOiB,SAAc,gBAChE,CAAChB,EAAkBD,CAAK,GAAKK,EAAgB,SAASL,EAAM,IAAI,EAErEQ,EAASR,CAAK,IACZK,EAAgB,SAASL,EAAMG,IAAO,GAAKH,EAAMkB,OAAY,4BAAuB,GAEnFT,EAAQT,CAAK,CAAC,CAAC,KAAKY,CAAa,CAC1C,CAiBA,SAAgBO,EAAkB,EAA6C,CAC7E,GAAI,OAAOnB,GAAU,WAAYA,EAAgB,OACjD,GAAM,CAAE,QAASA,EACjB,GAAI,OAAOoB,GAAS,SAAU,OAAO,OAAO,SAASA,CAAI,EAAIA,EAAO,IAAA,GACpE,GAAI,OAAOA,GAAS,UAAYA,EAAK,OAAS,GAAKA,EAAK,QAAU,GAChE,OAAOA,CAGX"}
package/dist/index.cjs CHANGED
@@ -1282,15 +1282,12 @@ function galaChainUserRef(value, field) {
1282
1282
  //#endregion
1283
1283
  //#region src/utils/eip712.ts
1284
1284
  /**
1285
- * Genuine EIP-712 typed-data signing for the four v2 dex-contract operations proven (2026-09-16,
1286
- * live bisection against stage — see defi-backend's `chain-findings-artifact` memory /
1287
- * https://claude.ai/artifact/3N9MevSjoQdU7gqnVB3dfU) to recover the `client|` identity correctly
1288
- * via `eth_signTypedData_v4`, unlike `personal_sign` (which only ever resolves the bare `eth|`
1289
- * form — see `BrowserWalletSigner`'s own doc comment). Mirrors frontend_v2's
1290
- * `src/Services/eip712Types.ts` + `readWriteUtilsV2.ts`'s `EIP712_FIELD_COMPLETERS` exactly —
1291
- * ported here rather than shared as a package because the SDKs have no frontend_v2 dependency
1292
- * and should not gain one for four small functions. (Moved from gswap-sdk with the rest of the
1293
- * signing closure; the four methods are dex-contract methods, the derivation is generic.)
1285
+ * Genuine EIP-712 typed-data signing for the four v2 dex-contract operations, proven by a live
1286
+ * bisection against the staging chain to recover the `client|` identity correctly via
1287
+ * `eth_signTypedData_v4`, unlike `personal_sign` (which only ever resolves the bare `eth|` form;
1288
+ * see `BrowserWalletSigner`'s own doc comment). The field completers mirror the web app's
1289
+ * typed-data builders exactly. (Moved from gswap-sdk with the rest of the signing closure; the
1290
+ * four methods are dex-contract methods, the derivation is generic.)
1294
1291
  */
1295
1292
  /**
1296
1293
  * Derives the EIP-712 `types` for a DTO from its runtime shape.
@@ -1358,10 +1355,10 @@ function generateEIP712Types(typeName, params) {
1358
1355
  return types;
1359
1356
  }
1360
1357
  /**
1361
- * Builds the EIP-712 domain from the wallet's LIVE `eth_chainId` result, exactly like frontend_v2
1362
- * (DEFI-1895): a wallet hashes whatever domain it is handed, and MetaMask refuses a `chainId` that
1363
- * differs from its active network, so a hardcoded `1` breaks every wallet that is not on Mainnet.
1364
- * defi-backend recovers the signer from the `domain` the payload carries (live-proven for chain
1358
+ * Builds the EIP-712 domain from the wallet's LIVE `eth_chainId` result: a wallet hashes whatever
1359
+ * domain it is handed, and MetaMask refuses a `chainId` that differs from its active network, so
1360
+ * a hardcoded `1` breaks every wallet that is not on Mainnet.
1361
+ * The backend recovers the signer from the `domain` the payload carries (live-proven for chain
1365
1362
  * ids 1, 56 and 11155111), so following the wallet is correct on every network.
1366
1363
  *
1367
1364
  * @param chainId - The raw `eth_chainId` result: a `0x` hex string (the JSON-RPC form) or an integer.
@@ -1483,7 +1480,7 @@ function buildEIP712Payload(methodName, dto) {
1483
1480
  *
1484
1481
  * Every function here is pinned byte-for-byte to the signatures produced by `@gala-chain/api`
1485
1482
  * (`serialize`, `signatures.getSignature`), `@gala-chain/connect`, the Gala Wallet extension and
1486
- * frontend_v2 by the golden-vector suite in `tests/signing-golden.test.ts`.
1483
+ * the gSwap web app by the golden-vector suite in `tests/signing-golden.test.ts`.
1487
1484
  */
1488
1485
  const textEncoder$1 = new TextEncoder();
1489
1486
  function toDeterministicNode(node) {
@@ -1554,15 +1551,15 @@ function personalSignPrefixFor(dto) {
1554
1551
  return calculatePersonalSignPrefix(serialize(withoutPrefix));
1555
1552
  }
1556
1553
  /**
1557
- * The `@gala-chain/connect`-style prefix frontend_v2 puts in the body of an EIP-712 write: the
1554
+ * The `@gala-chain/connect`-style prefix the gSwap web app puts in the body of an EIP-712 write: the
1558
1555
  * EIP-191 header whose number counts the prefix string ITSELF plus the body (the UTF-8 length of
1559
1556
  * `getPayloadToSign({ ...dto, prefix })`), found by fixpoint because adding the prefix changes the
1560
1557
  * length (a body of 99 bytes settles on 101).
1561
1558
  *
1562
1559
  * It is NOT a personal-sign prefix (a personal-sign write with this value recovers a phantom
1563
1560
  * signer; use `personalSignPrefixFor`). Under EIP-712 the field is an untyped extra that the
1564
- * typed-data hash ignores and defi-backend recomputes, so it only exists to keep the submitted
1565
- * body byte-identical to what frontend_v2 has always sent.
1561
+ * typed-data hash ignores and the backend recomputes, so it only exists to keep the submitted
1562
+ * body byte-identical to what the gSwap web app has always sent.
1566
1563
  */
1567
1564
  function fixpointPrefixFor(dto) {
1568
1565
  const withoutPrefix = { ...dto };
@@ -1731,8 +1728,8 @@ function normalizeEthereumAccount(address, allowGalaPrefix, field = "walletAddre
1731
1728
  * The account handed to Gala Wallet as the signer address. An Ethereum account is held to the
1732
1729
  * same strict check as ever (`0x` plus 40 hex digits; `eth|` plus 40 hex digits is normalized to
1733
1730
  * it; `eth|0x...` is refused). A GalaChain id the wallet can also be asked to sign for is passed
1734
- * through verbatim: `client|` plus 24 hex digits, or the bare 24 hex digits that frontend_v2 keeps
1735
- * in `state.user.wallet` after a direct `client|` login. Nothing else is accepted.
1731
+ * through verbatim: `client|` plus 24 hex digits, or the bare 24 hex digits that a web app keeps
1732
+ * after a direct `client|` login. Nothing else is accepted.
1736
1733
  */
1737
1734
  function normalizeGalaWalletAccount(address) {
1738
1735
  assertNoEthZeroXPrefix(address, "walletAddress");
@@ -1952,11 +1949,10 @@ function createLazyPrivateKeySigner(getPrivateKey, options = {}) {
1952
1949
  *
1953
1950
  * `scheme: 'personal-sign'` calls
1954
1951
  * `gala_signChainDto([serialize({ ...dto, prefix }), walletAddress, methodName])` and REQUIRES
1955
- * a wallet build that contains wallet_extension commit 34ca4e4 (strips the embedded `prefix`
1956
- * field and hashes `prefix` + the prefix-less canonical body, the chain's scheme). Wallets
1957
- * released before that fix hash the string with the `prefix` field still inside it and the
1958
- * signature recovers to an address nobody holds, so only opt in once the fixed wallet is
1959
- * released. See SIGNING-PARITY.md.
1952
+ * a Gala Wallet build that strips the embedded `prefix` field and hashes `prefix` + the
1953
+ * prefix-less canonical body (the chain's scheme). Wallet builds that predate that fix hash the
1954
+ * string with the `prefix` field still inside it and the signature recovers to an address
1955
+ * nobody holds, so only opt in once the wallet you target has the fix.
1960
1956
  */
1961
1957
  var GalaWalletSigner = class {
1962
1958
  /** The wallet address supplied to Gala Wallet for each signing request. */
@@ -1975,9 +1971,9 @@ var GalaWalletSigner = class {
1975
1971
  * @param walletAddress - The account passed to Gala Wallet as the signer address. An Ethereum
1976
1972
  * account is `0x` plus 40 hex digits (Gala Wallet's `eth|...` form is normalized to it and held
1977
1973
  * to the same check); a GalaChain id is `client|` plus 24 hex digits, or the bare 24 hex digits
1978
- * frontend_v2 keeps for a direct `client|` login, and is passed through unchanged.
1974
+ * a web app keeps for a direct `client|` login, and is passed through unchanged.
1979
1975
  * @param options - Select native signing (default) or personal-sign explicitly.
1980
- * `'personal-sign'` requires a Gala Wallet build with wallet_extension commit 34ca4e4.
1976
+ * `'personal-sign'` requires a Gala Wallet build that signs the bare serialized DTO.
1981
1977
  * `selectAddress` is the identity (`client|...` / `eth|...`) Gala Wallet is switched to with
1982
1978
  * `setAddress` before every signature, when the wallet offers it. `wallet` is the Gala Wallet
1983
1979
  * object to sign through (the one an EIP-6963 announcement or a wallet provider holds); without
@@ -2092,9 +2088,8 @@ var BrowserWalletSigner = class {
2092
2088
  * String-key signing entry points for apps that hold a private key only briefly (the Gala Wallet
2093
2089
  * extension reads its session key at sign time and must not keep it in a long-lived object).
2094
2090
  *
2095
- * These are thin, byte-exact ports of the functions the wallet shipped in
2096
- * `wallet_extension/src/helpers/wallet/signing.ts` (including the fail-closed personal-sign
2097
- * payload resolver from its commit 34ca4e4), re-expressed over the SDK's own primitives. Every
2091
+ * These are thin, byte-exact ports of the functions the wallet shipped (including the
2092
+ * fail-closed personal-sign payload resolver), re-expressed over the SDK's own primitives. Every
2098
2093
  * function takes the key as a string (`0x`-optional hex, or base64) or as bytes, normalizes it per
2099
2094
  * call, and zeroes the normalized copy before returning, so nothing in this module retains a key.
2100
2095
  * A JavaScript string cannot be wiped; the caller owns the lifetime of the string it passes in.
@@ -2136,7 +2131,7 @@ function isPersonalSignHeader(prefix) {
2136
2131
  return prefix.startsWith(PERSONAL_SIGN_HEADER) && PERSONAL_SIGN_LENGTH_PATTERN.test(prefix.slice(26));
2137
2132
  }
2138
2133
  /**
2139
- * Top-level fields that would make the chain (`getPayloadToSign`) or defi-backend's personal-sign
2134
+ * Top-level fields that would make the chain (`getPayloadToSign`) or the swap backend's personal-sign
2140
2135
  * verifier hash something other than `prefix + serialize(dto minus prefix)`. An unsigned DTO from
2141
2136
  * a dApp never legitimately carries any of them, so they fail closed. Order is part of the error
2142
2137
  * message the wallet shows its user.
@@ -2374,7 +2369,7 @@ function leafEncoder(base) {
2374
2369
  const fixed = /^bytes([1-9][0-9]?)$/u.exec(base);
2375
2370
  if (fixed !== null) {
2376
2371
  const width = Number(fixed[1]);
2377
- if (width > 32 || String(width) !== fixed[1]) return void 0;
2372
+ if (width > 32) return void 0;
2378
2373
  return (value) => {
2379
2374
  const bytes = toBytes(value, base);
2380
2375
  if (bytes.length !== width) throw new GalaSDKError("TYPED_DATA_BYTES_LENGTH", {
@@ -2401,7 +2396,7 @@ function leafEncoder(base) {
2401
2396
  function parseType(type) {
2402
2397
  const match = TYPE_SYNTAX.exec(type);
2403
2398
  if (match === null) throw new GalaSDKError("TYPED_DATA_UNSUPPORTED_TYPE", { type });
2404
- const dimensions = [...(match[2] ?? "").matchAll(/\[([0-9]*)\]/gu)].map((dimension) => dimension[1] === "" ? -1 : Number(dimension[1]));
2399
+ const dimensions = [...match[2].matchAll(/\[([0-9]*)\]/gu)].map((dimension) => dimension[1] === "" ? -1 : Number(dimension[1]));
2405
2400
  return {
2406
2401
  base: match[1],
2407
2402
  dimensions
@@ -2470,19 +2465,19 @@ function createStructEncoder(rawTypes) {
2470
2465
  if (visiting.has(name)) throw new GalaSDKError("TYPED_DATA_CIRCULAR_TYPE", { typeName: name });
2471
2466
  if (checked.has(name)) return;
2472
2467
  visiting.add(name);
2473
- for (const child of children.get(name) ?? []) checkCircular(child);
2468
+ for (const child of children.get(name)) checkCircular(child);
2474
2469
  visiting.delete(name);
2475
2470
  checked.add(name);
2476
2471
  };
2477
2472
  checkCircular(primaryType);
2478
2473
  const dependencies = (name, found) => {
2479
- for (const child of children.get(name) ?? []) if (!found.has(child)) {
2474
+ for (const child of children.get(name)) if (!found.has(child)) {
2480
2475
  found.add(child);
2481
2476
  dependencies(child, found);
2482
2477
  }
2483
2478
  return found;
2484
2479
  };
2485
- const encodeOne = (name) => `${name}(${(fields.get(name) ?? []).map((field) => `${field.type} ${field.name}`).join(",")})`;
2480
+ const encodeOne = (name) => `${name}(${fields.get(name).map((field) => `${field.type} ${field.name}`).join(",")})`;
2486
2481
  const typeHashes = /* @__PURE__ */ new Map();
2487
2482
  for (const name of names) {
2488
2483
  const sorted = [...dependencies(name, /* @__PURE__ */ new Set())].filter((dep) => dep !== name).sort();
@@ -2502,7 +2497,6 @@ function createStructEncoder(rawTypes) {
2502
2497
  function hashStruct(typeName, value) {
2503
2498
  const list = fields.get(typeName);
2504
2499
  const typeHash = typeHashes.get(typeName);
2505
- if (list === void 0 || typeHash === void 0) throw new Error(`Internal error: no encoder for struct ${typeName}`);
2506
2500
  if (value === null || typeof value !== "object" || Array.isArray(value)) throw new GalaSDKError("TYPED_DATA_STRUCT_NOT_OBJECT", { typeName });
2507
2501
  const record = value;
2508
2502
  const words = list.map((field) => {
@@ -2573,7 +2567,7 @@ const REJECTION_NAME = "UserRejectedRequestError";
2573
2567
  /**
2574
2568
  * Wordings of a decline, matched case-insensitively as substrings. This is a LAST RESORT for
2575
2569
  * wallets that set neither a `code` nor a `name`: it reads a third party's text, so it is broad on
2576
- * purpose (a superset of the matchers the Gala wallet and frontend_v2 used) and can in principle
2570
+ * purpose (a superset of the matchers the Gala wallet and gSwap web app used) and can in principle
2577
2571
  * match an unrelated message that uses these words.
2578
2572
  */
2579
2573
  const REJECTION_PHRASES = [
@@ -2721,7 +2715,7 @@ async function signPreSend(signer, method, dto) {
2721
2715
  * fallback. It is the version in the default `User-Agent` (`GalaChain-SDK/<version>`) of every SDK
2722
2716
  * request, whichever product SDK sends it.
2723
2717
  */
2724
- const GALA_CORE_SDK_VERSION = "1.0.0-rc.7";
2718
+ const GALA_CORE_SDK_VERSION = "1.0.0";
2725
2719
 
2726
2720
  //#endregion
2727
2721
  //#region src/utils/transport.ts
@@ -2782,7 +2776,7 @@ function buildRequestHeaders(wire, parts = {}) {
2782
2776
  entries.set(name.toLowerCase(), [name, value]);
2783
2777
  }
2784
2778
  };
2785
- if ((wire === null || wire === void 0 ? void 0 : wire.userAgent) !== false) put({ "User-Agent": (wire === null || wire === void 0 ? void 0 : wire.userAgent) ?? `GalaChain-SDK/${"1.0.0-rc.7"}` });
2779
+ if ((wire === null || wire === void 0 ? void 0 : wire.userAgent) !== false) put({ "User-Agent": (wire === null || wire === void 0 ? void 0 : wire.userAgent) ?? `GalaChain-SDK/${"1.0.0"}` });
2786
2780
  put(parts.defaults);
2787
2781
  put(wire === null || wire === void 0 ? void 0 : wire.headers);
2788
2782
  if (parts.json === true && !entries.has("content-type")) put({ "Content-Type": "application/json" });
@@ -3314,8 +3308,8 @@ function isValidUniqueKey(uniqueKey) {
3314
3308
  //#endregion
3315
3309
  //#region src/utils/unique_key.ts
3316
3310
  /**
3317
- * The `uniqueKey` prefix frontend_v2 and wallet_extension have always sent
3318
- * (`galaswap-operation-<uuid>`). defi-backend does not depend on it: the chain-write verifier
3311
+ * The `uniqueKey` prefix the Gala Wallet and the gSwap web app have always sent
3312
+ * (`galaswap-operation-<uuid>`). The backend does not depend on it: the chain-write verifier
3319
3313
  * only requires a non-empty key of at most 256 characters, and apply-results accepts
3320
3314
  * `[A-Za-z0-9._:-]{1,128}`; the only code that mints a prefixed key itself is the server-side v1
3321
3315
  * trade builder, which nothing reads back by prefix.