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

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 e from"../_virtual/_@oxc-project_runtime@0.154.0/helpers/esm/defineProperty.js";import{GalaSDKError as t,isGalaError as n}from"./gala_sdk_error.js";import{assertNoEthZeroXPrefix as r}from"../writes/identity.js";import{EIP712_CAPABLE_METHODS as i,buildEIP712Payload as a,eip712DomainFor as o}from"../utils/eip712.js";import{ethAddressOfPrivateKey as s,fixpointPrefixFor as c,normalizePrivateKey as l,personalSignPrefixFor as u,serialize as d,signNative as f}from"../utils/signing.js";function p(){let e=globalThis.window?.gala;if(!e)throw new t(`GALA_WALLET_NOT_AVAILABLE`,{});return e}function m(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new t(`INVALID_SIGNATURE`,{scheme:`native`});return e}function h(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new t(`INVALID_SIGNATURE`,{scheme:`personal-sign`});return e}function g(e){r(e,`account`);let t=/^(?:eth\||0x)([0-9a-fA-F]{40})$/u.exec(e);return t?.[1]===void 0?void 0:`0x${t[1]}`}function _(e,n,i=`walletAddress`){r(e,i);let a=n?g(e)??e:e;if(!/^0x[0-9a-fA-F]{40}$/u.test(a))throw new t(`INVALID_WALLET_ADDRESS`,{field:i,value:e});return a}function v(e){r(e,`walletAddress`);let n=/^eth\|([0-9a-fA-F]{40})$/u.exec(e);if(n?.[1]!==void 0)return`0x${n[1]}`;if(/^0x[0-9a-fA-F]{40}$/u.test(e)||/^(?:client\|)?[0-9a-fA-F]{24}$/u.test(e))return e;throw new t(`INVALID_WALLET_ADDRESS`,{field:`walletAddress`,value:e})}function y(e){if(r(e,`selectAddress`),!/^(?:eth\|[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\|)?[0-9a-fA-F]{24})$/u.test(e))throw new t(`INVALID_WALLET_ADDRESS`,{field:`selectAddress`,value:e})}const b=/* @__PURE__ */ new WeakMap;function x(e,t,n){let{setAddress:r}=e;if(t===void 0||typeof r!=`function`)return n();let i=(b.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>(await r.call(e,t),n()));return b.set(e,i),i}function S(e,t,n,r){let i=u(t),a={...t,prefix:i},o=r===void 0?[d(t),n]:[d(a),n,r];return e.request({method:r===void 0?`personal_sign`:`gala_signChainDto`,params:o}).then(e=>({...a,signature:h(e)}))}async function C(e,t,n,r){let{completedDto:i,types:s}=a(t,n),l=o(await e.request({method:`eth_chainId`,params:[]})),u=c(i),d={...i,prefix:u},f=[{name:`name`,type:`string`},{name:`chainId`,type:`uint256`}],p={domain:l,types:{...s,EIP712Domain:f},primaryType:t,message:d},m=await e.request({method:`eth_signTypedData_v4`,params:[r,JSON.stringify(p)]});return{...d,signature:h(m),types:s,domain:l}}var w=class{constructor(t){e(this,`privateKey`,void 0),this.privateKey=l(t)}signObject(e,t){let n=f(this.privateKey,t);return Promise.resolve({...t,signature:n})}};async function T(e){try{return await e()}catch(e){throw n(e)?e:new t(`KEY_PROVIDER_FAILED`,{},{cause:e})}}function E(e,n={}){let r=n.expectedAddress,i=r===void 0?void 0:_(r,!0,`expectedAddress`).toLowerCase();return{async signObject(n,r){let a=await T(e);if(typeof a!=`string`||a===``)throw new t(`INVALID_PRIVATE_KEY`,{reason:`no_key_provided`});let o=l(a);try{if(i!==void 0&&s(o)!==i)throw new t(`SIGNER_ADDRESS_MISMATCH`,{});return{...r,signature:f(o,r)}}finally{o.fill(0)}}}}var D=class{constructor(t,n={}){e(this,`walletAddress`,void 0),e(this,`scheme`,void 0),e(this,`selectAddress`,void 0),e(this,`wallet`,void 0),this.walletAddress=v(t),this.scheme=n.scheme??`native`,n.selectAddress!==void 0&&y(n.selectAddress),this.selectAddress=n.selectAddress,this.wallet=n.wallet}async signObject(e,t){let n=this.wallet??p();return x(n,this.selectAddress,async()=>{if(this.scheme===`personal-sign`)return S(n,t,this.walletAddress,e);let r=await n.request({method:`gala_signChainDto`,params:[d(t),this.walletAddress,e,`native`]});return{...t,signature:m(r)}})}},O=class{constructor(t,n,r={}){this.provider=t,e(this,`walletAddress`,void 0),e(this,`scheme`,void 0),this.walletAddress=_(n,!1),this.scheme=r.scheme??`personal-sign`}signObject(e,t){return this.scheme===`eip712`&&i.has(e)?C(this.provider,e,t,this.walletAddress):S(this.provider,t,this.walletAddress)}};export{O as BrowserWalletSigner,D as GalaWalletSigner,w as PrivateKeySigner,E as createLazyPrivateKeySigner,g as ethereumAddressOfAccount,x as withGalaWalletIdentity};
1
+ import e from"../_virtual/_@oxc-project_runtime@0.154.0/helpers/esm/defineProperty.js";import{GalaSDKError as t,isGalaError as n}from"./gala_sdk_error.js";import{assertNoEthZeroXPrefix as r}from"../writes/identity.js";import{EIP712_CAPABLE_METHODS as i,buildEIP712Payload as a,eip712DomainFor as o}from"../utils/eip712.js";import{ethAddressOfPrivateKey as s,fixpointPrefixFor as c,normalizePrivateKey as l,personalSignPrefixFor as u,serialize as d,signNative as f}from"../utils/signing.js";function p(){let e=globalThis.window?.gala;if(!e)throw new t(`GALA_WALLET_NOT_AVAILABLE`,{});return e}function m(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new t(`INVALID_SIGNATURE`,{scheme:`native`});return e}function h(e){if(typeof e!=`string`||!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(e))throw new t(`INVALID_SIGNATURE`,{scheme:`personal-sign`});return e}function g(e){r(e,`account`);let t=/^(?:eth\||0x)([0-9a-fA-F]{40})$/u.exec(e);return t?.[1]===void 0?void 0:`0x${t[1]}`}function _(e,n,i=`walletAddress`){r(e,i);let a=n?g(e)??e:e;if(!/^0x[0-9a-fA-F]{40}$/u.test(a))throw new t(`INVALID_WALLET_ADDRESS`,{field:i,value:e});return a}function v(e){r(e,`walletAddress`);let n=/^eth\|([0-9a-fA-F]{40})$/u.exec(e);if(n?.[1]!==void 0)return`0x${n[1]}`;if(/^0x[0-9a-fA-F]{40}$/u.test(e)||/^(?:client\|)?[0-9a-fA-F]{24}$/u.test(e))return e;throw new t(`INVALID_WALLET_ADDRESS`,{field:`walletAddress`,value:e})}function y(e){if(r(e,`selectAddress`),!/^(?:eth\|[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\|)?[0-9a-fA-F]{24})$/u.test(e))throw new t(`INVALID_WALLET_ADDRESS`,{field:`selectAddress`,value:e})}const b=/* @__PURE__ */ new WeakMap;function x(e,t,n){let{setAddress:r}=e;if(t===void 0||typeof r!=`function`)return n();let i=(b.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>(await r.call(e,t),n()));return b.set(e,i),i}function S(e,t,n,r){let i=u(t),a={...t,prefix:i},o=r===void 0?[d(t),n]:[d(a),n,r];return e.request({method:r===void 0?`personal_sign`:`gala_signChainDto`,params:o}).then(e=>({...a,signature:h(e)}))}async function C(e,t,n,r,i){let{completedDto:s,types:l}=a(t,n),u=o(await e.request({method:`eth_chainId`,params:[]}),i),d=c(s),f={...s,prefix:d},p=[{name:`name`,type:`string`},{name:`chainId`,type:`uint256`}],m={domain:u,types:{...l,EIP712Domain:p},primaryType:t,message:f},g=await e.request({method:`eth_signTypedData_v4`,params:[r,JSON.stringify(m)]});return{...f,signature:h(g),types:l,domain:u}}var w=class{constructor(t){e(this,`privateKey`,void 0),this.privateKey=l(t)}signObject(e,t){let n=f(this.privateKey,t);return Promise.resolve({...t,signature:n})}};async function T(e){try{return await e()}catch(e){throw n(e)?e:new t(`KEY_PROVIDER_FAILED`,{},{cause:e})}}function E(e,n={}){let r=n.expectedAddress,i=r===void 0?void 0:_(r,!0,`expectedAddress`).toLowerCase();return{async signObject(n,r){let a=await T(e);if(typeof a!=`string`||a===``)throw new t(`INVALID_PRIVATE_KEY`,{reason:`no_key_provided`});let o=l(a);try{if(i!==void 0&&s(o)!==i)throw new t(`SIGNER_ADDRESS_MISMATCH`,{});return{...r,signature:f(o,r)}}finally{o.fill(0)}}}}var D=class{constructor(t,n={}){e(this,`walletAddress`,void 0),e(this,`scheme`,void 0),e(this,`selectAddress`,void 0),e(this,`wallet`,void 0),this.walletAddress=v(t),this.scheme=n.scheme??`native`,n.selectAddress!==void 0&&y(n.selectAddress),this.selectAddress=n.selectAddress,this.wallet=n.wallet}async signObject(e,t){let n=this.wallet??p();return x(n,this.selectAddress,async()=>{if(this.scheme===`personal-sign`)return S(n,t,this.walletAddress,e);let r=await n.request({method:`gala_signChainDto`,params:[d(t),this.walletAddress,e,`native`]});return{...t,signature:m(r)}})}},O=class{constructor(t,n,r={}){this.provider=t,e(this,`walletAddress`,void 0),e(this,`scheme`,void 0),e(this,`eip712DomainName`,void 0),this.walletAddress=_(n,!1),this.scheme=r.scheme??`personal-sign`,this.eip712DomainName=r.eip712DomainName}signObject(e,t){return this.scheme===`eip712`&&i.has(e)?C(this.provider,e,t,this.walletAddress,this.eip712DomainName):S(this.provider,t,this.walletAddress)}};export{O as BrowserWalletSigner,D as GalaWalletSigner,w as PrivateKeySigner,E as createLazyPrivateKeySigner,g as ethereumAddressOfAccount,x as withGalaWalletIdentity};
2
2
  //# sourceMappingURL=signers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"signers.js","names":["globalObject","_defineProperty","getWalletProvider","wallet","GalaSDKError","getNativeSignature","value","getPersonalSignature","ethereumAddressOfAccount","assertNoEthZeroXPrefix","account","match","normalizeEthereumAccount","address","field","normalized","allowGalaPrefix","normalizeGalaWalletAccount","eth","assertWalletIdentity","identity","walletIdentityQueue","withGalaWalletIdentity","setAddress","signWith","run","personalSign","prefix","personalSignPrefixFor","dto","payload","params","methodName","serialize","walletAddress","provider","signEIP712","buildEIP712Payload","domain","eip712DomainFor","fixpointPrefixFor","completedDto","message","eip712Domain","types","PrivateKeySigner","normalizePrivateKey","privateKey","signature","signNative","keyFrom","getPrivateKey","cause","isGalaError","createLazyPrivateKeySigner","expected","options","expectedLower","provided","key","ethAddressOfPrivateKey","GalaWalletSigner","BrowserWalletSigner","EIP712_CAPABLE_METHODS"],"sources":["../../../src/classes/signers.ts"],"sourcesContent":["import { GalaSDKError, isGalaError } from './gala_sdk_error.js';\nimport { assertNoEthZeroXPrefix } from '../writes/identity.js';\nimport {\n buildEIP712Payload,\n EIP712_CAPABLE_METHODS,\n eip712DomainFor,\n type EIP712DomainValue,\n type EIP712Types,\n} from '../utils/eip712.js';\nimport {\n ethAddressOfPrivateKey,\n fixpointPrefixFor,\n normalizePrivateKey,\n personalSignPrefixFor,\n serialize,\n signNative,\n} from '../utils/signing.js';\n\n// Personal-sign prefix, computed the way THE CHAIN verifies it.\n//\n// GalaChain (SDK 3.x) recovers a personal-signed DTO from\n// keccak256(<prefix field> + <canonical JSON of the DTO WITHOUT the prefix field>)\n// and a browser wallet's `personal_sign` (EIP-191) hashes\n// \"\\u0019Ethereum Signed Message:\\n\" + <byte length of message> + <message>.\n// They agree exactly when the wallet signs the bare canonical DTO and `prefix` is the EIP-191\n// header for that message's UTF-8 BYTE length. Any other message still yields a valid-looking\n// signature — it just recovers to an address nobody holds. This SDK used to embed `prefix` in\n// the signed message (the SDK 1.10 client recipe): observed on stage 2026-09-23, such a\n// MetaMask-signed CreatePool executed on chain under a phantom creator, and the swap backend's\n// write guard now rejects that shape outright.\n//\n// `@gala-chain/connect`'s prefix helper must NOT be used for wallet `personal_sign`: its\n// fixpoint counts the prefix itself and targets the SDK's raw-payload signer. The same header\n// is also what Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepends before hashing,\n// so one value serves both paths.\n//\n// The header itself is computed by `personalSignPrefixFor` in ../utils/signing.ts.\n\n/** The signing schemes supported by the Gala Wallet signer. */\nexport type GalaWalletScheme = 'native' | 'personal-sign';\n\n/** The request surface used by an EIP-1193 browser wallet. */\nexport interface BrowserWalletProvider {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n}\n\n/** The Gala Wallet extension's API (`window.gala`, or the same object from an EIP-6963 announcement). */\nexport interface GalaWalletApi {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n /** Gala Wallet's \"act as this account\" switch; absent on other providers. */\n setAddress?: (address: string) => Promise<void>;\n}\n\ninterface WindowWithGala {\n gala?: GalaWalletApi;\n}\n\ninterface GlobalWithWindow {\n window?: WindowWithGala;\n}\n\n/** A DTO together with the signature that belongs in the gateway request body. */\nexport type SignedDto<T extends Record<string, unknown>> = T & { signature: string };\n\n/**\n * A signer for complete GalaChain write bodies.\n *\n * Implementations return the DTO fields together with the signature that belongs in the\n * gateway request body. Signer identity is recovered from that signature; implementations do\n * not add signer hints, typed-data metadata, or a domain.\n */\nexport interface GalaChainSigner {\n /**\n * Signs a DTO for a named GalaChain contract method.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n signObject<T extends Record<string, unknown>>(methodName: string, dto: T): Promise<SignedDto<T>>;\n}\n\nfunction getWalletProvider(): GalaWalletApi {\n const globalObject = globalThis as GlobalWithWindow;\n const wallet = globalObject.window?.gala;\n if (!wallet) {\n throw new GalaSDKError('GALA_WALLET_NOT_AVAILABLE', {});\n }\n return wallet;\n}\n\nfunction getNativeSignature(value: unknown): string {\n if (typeof value !== 'string') {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n // 130 hex digits (r || s || v), bare as Gala Wallet returns it or `0x`-prefixed; passed on\n // verbatim, because the backend recovers the signer from either spelling.\n if (!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n return value;\n}\n\nfunction getPersonalSignature(value: unknown): string {\n if (typeof value !== 'string' || !/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'personal-sign' });\n }\n return value;\n}\n\n/**\n * The `0x`-prefixed Ethereum address a Gala account is signed by, or `undefined` when the account\n * names no key (a `client|` alias or a bare GalaChain id is not derivable from a key). Accepts\n * `0x` plus 40 hex digits and `eth|` plus 40 hex digits; the caller's casing is kept. `eth|0x...`\n * is not an address form and is refused. For {@link LazyPrivateKeySignerOptions.expectedAddress}, which should only be set for\n * an account whose key can be checked.\n *\n * @example\n * ```ts\n * createLazyPrivateKeySigner(getKey, { expectedAddress: ethereumAddressOfAccount(account) });\n * ```\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` for `eth|0x...` (refused, never read as\n * \"names no key\", which would switch a signer's address check off).\n */\nexport function ethereumAddressOfAccount(account: string): string | undefined {\n assertNoEthZeroXPrefix(account, 'account');\n const match = /^(?:eth\\||0x)([0-9a-fA-F]{40})$/u.exec(account);\n return match?.[1] === undefined ? undefined : `0x${match[1]}`;\n}\n\nfunction normalizeEthereumAccount(\n address: string,\n allowGalaPrefix: boolean,\n field = 'walletAddress',\n): string {\n assertNoEthZeroXPrefix(address, field);\n const normalized = allowGalaPrefix ? (ethereumAddressOfAccount(address) ?? address) : address;\n if (!/^0x[0-9a-fA-F]{40}$/u.test(normalized)) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field, value: address });\n }\n // The caller's casing is kept on purpose: the Gala web apps and the wallet hand the wallet the\n // checksummed account, and EIP-1193 / Gala Wallet accept any case, so passing the value through\n // unchanged is the only choice that cannot differ from what they send.\n return normalized;\n}\n\n/**\n * The account handed to Gala Wallet as the signer address. An Ethereum account is held to the\n * same strict check as ever (`0x` plus 40 hex digits; `eth|` plus 40 hex digits is normalized to\n * it; `eth|0x...` is refused). A GalaChain id the wallet can also be asked to sign for is passed\n * through verbatim: `client|` plus 24 hex digits, or the bare 24 hex digits that a web app keeps\n * after a direct `client|` login. Nothing else is accepted.\n */\nfunction normalizeGalaWalletAccount(address: string): string {\n assertNoEthZeroXPrefix(address, 'walletAddress');\n const eth = /^eth\\|([0-9a-fA-F]{40})$/u.exec(address);\n if (eth?.[1] !== undefined) return `0x${eth[1]}`;\n if (/^0x[0-9a-fA-F]{40}$/u.test(address) || /^(?:client\\|)?[0-9a-fA-F]{24}$/u.test(address)) {\n return address;\n }\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field: 'walletAddress', value: address });\n}\n\n/** An identity Gala Wallet can act as: an account form above, any `eth|`/`client|` alias, verbatim. */\nfunction assertWalletIdentity(identity: string): void {\n assertNoEthZeroXPrefix(identity, 'selectAddress');\n if (\n !/^(?:eth\\|[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\\|)?[0-9a-fA-F]{24})$/u.test(identity)\n ) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field: 'selectAddress', value: identity });\n }\n}\n\n/** Provider-wide queue: `setAddress` + the signature request must not interleave across signers. */\nconst walletIdentityQueue = new WeakMap<object, Promise<unknown>>();\n\n/**\n * Runs `signWith` with `identity` selected on a Gala Wallet that supports `setAddress`. Gala\n * Wallet holds ONE current account, so two signatures for different identities in flight at once\n * would sign as whichever selection came last; the pair (select, sign) is therefore serialized\n * per wallet object, across every signer and provider that signs through it\n * (`GalaWalletSigner`, `./providers`' `GalaWalletProvider`). A failed selection fails the\n * signature (nothing is requested). Without an identity, or on a wallet without `setAddress`, it\n * just runs `signWith`.\n *\n * @example\n * ```typescript\n * const signature = await withGalaWalletIdentity(window.gala, 'eth|70997970C51812dc3A010C7d01b50e0d17dc79C8', () =>\n * window.gala.request({ method: 'personal_sign', params: [hexMessage, address] }),\n * );\n * ```\n */\nexport function withGalaWalletIdentity<T>(\n wallet: GalaWalletApi,\n identity: string | undefined,\n signWith: () => Promise<T>,\n): Promise<T> {\n const { setAddress } = wallet;\n if (identity === undefined || typeof setAddress !== 'function') return signWith();\n const previous = walletIdentityQueue.get(wallet) ?? Promise.resolve();\n const run = previous\n .catch(() => undefined)\n .then(async () => {\n await setAddress.call(wallet, identity);\n return signWith();\n });\n walletIdentityQueue.set(wallet, run);\n return run;\n}\n\nfunction personalSign<T extends Record<string, unknown>>(\n provider: GalaWalletApi | BrowserWalletProvider,\n dto: T,\n walletAddress: string,\n methodName?: string,\n): Promise<T & { prefix: string; signature: string }> {\n const prefix = personalSignPrefixFor(dto);\n const payload = { ...dto, prefix };\n // A browser wallet's `personal_sign` applies the EIP-191 header ITSELF, so it must sign the\n // bare DTO; Gala Wallet's `gala_signChainDto` (personal-sign scheme) instead extracts the\n // `prefix` field from what it is handed and prepends it before hashing, so it is handed the\n // prefixed payload. Both submit `{ ...dto, prefix, signature }`.\n const params =\n methodName !== undefined\n ? [serialize(payload), walletAddress, methodName]\n : [serialize(dto), walletAddress];\n\n return provider\n .request({ method: methodName !== undefined ? 'gala_signChainDto' : 'personal_sign', params })\n .then((value) => ({ ...payload, signature: getPersonalSignature(value) }));\n}\n\n/**\n * Signs a DTO via genuine EIP-712 (`eth_signTypedData_v4`) — correctly resolves the `client|`\n * identity, unlike `personal_sign`, for the operations in `EIP712_CAPABLE_METHODS`.\n *\n * Constructs the raw JSON-RPC payload by hand (`{domain, types: {...types, EIP712Domain},\n * primaryType, message}`) rather than depending on ethers.js, matching exactly what\n * `ethers.TypedDataEncoder.getPayload`/`Wallet.signTypedData` produce internally — verified\n * byte-for-byte equivalent (same recovered address from the same signature against both\n * constructions) before this shipped, since the core SDK deliberately has no ethers dependency.\n */\nasync function signEIP712<T extends Record<string, unknown>>(\n provider: BrowserWalletProvider,\n methodName: string,\n dto: T,\n walletAddress: string,\n): Promise<T & { types: EIP712Types; domain: EIP712DomainValue; signature: string }> {\n const { completedDto, types } = buildEIP712Payload(methodName, dto);\n // The wallet's LIVE chain id, read on every signature: a user can switch networks after\n // connecting, and a cached or hardcoded id would sign a domain MetaMask itself rejects.\n const domain = eip712DomainFor(await provider.request({ method: 'eth_chainId', params: [] }));\n // The body `prefix` is not part of the EIP-712 `types`, so it is never hashed; it carries the\n // connect-style fixpoint value only to keep the submitted body byte-identical to what the Gala\n // web apps have always sent.\n const prefix = fixpointPrefixFor(completedDto);\n const message = { ...completedDto, prefix };\n const eip712Domain = [\n { name: 'name', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n ];\n const payload = {\n domain,\n types: { ...types, EIP712Domain: eip712Domain },\n primaryType: methodName,\n message,\n };\n\n const value = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [walletAddress, JSON.stringify(payload)],\n });\n // Key order matches the body the Gala web apps submit: ..., prefix, signature, types, domain.\n return {\n ...(message as T & { prefix: string }),\n signature: getPersonalSignature(value),\n types,\n domain,\n };\n}\n\n/**\n * A GalaChain native signer backed by a secp256k1 private key.\n *\n * Native signing produces the bare GalaChain signature format, without a personal-sign prefix\n * or EIP-712 metadata. The private-key identity is recovered by the chain.\n */\nexport class PrivateKeySigner implements GalaChainSigner {\n private readonly privateKey: Uint8Array;\n\n /**\n * Creates a native signer from a hex or base64 secp256k1 private key.\n *\n * @example\n * ```typescript\n * const signer = new PrivateKeySigner('1'.padStart(64, '0'));\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n constructor(privateKey: string) {\n this.privateKey = normalizePrivateKey(privateKey);\n }\n\n /**\n * Signs the DTO with GalaChain native signing.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const signature = signNative(this.privateKey, dto);\n return Promise.resolve({ ...dto, signature });\n }\n}\n\n/** Supplies a private key at sign time: a hex/base64 string, possibly fetched asynchronously. */\nexport type PrivateKeyProvider = () => Promise<string> | string;\n\n/** Options for {@link createLazyPrivateKeySigner}. */\nexport interface LazyPrivateKeySignerOptions {\n /**\n * When set, every signature first checks that the fetched key belongs to this account (`0x...`\n * or the Gala `eth|<40 hex>` form, case-insensitive; `eth|0x...` is refused at creation) and\n * refuses to sign otherwise (`SIGNER_ADDRESS_MISMATCH`). Use it when the key lives in a slot another surface can switch\n * between the moment a request was approved and the moment it is signed.\n */\n expectedAddress?: string | undefined;\n}\n\n/**\n * Calls the app's key provider. Whatever it throws or rejects with is the app's own failure to\n * produce a key before anything was signed or sent, so it becomes `KEY_PROVIDER_FAILED` (the\n * original is `cause`); an SDK error is already catalogued and passes through.\n */\nasync function keyFrom(getPrivateKey: PrivateKeyProvider): Promise<unknown> {\n try {\n return await getPrivateKey();\n } catch (cause: unknown) {\n throw isGalaError(cause) ? cause : new GalaSDKError('KEY_PROVIDER_FAILED', {}, { cause });\n }\n}\n\n/**\n * Creates the native-signing equivalent of {@link PrivateKeySigner} for apps that must not hold a\n * key in a long-lived object (an extension that reads its session key at sign time).\n *\n * `getPrivateKey` is called once per `signObject` call, never cached, never shared between calls\n * (concurrent signatures each fetch their own key), and the normalized key bytes are zeroed\n * before `signObject` settles, also on failure. A rejection or exception from `getPrivateKey` (the\n * app's \"wallet is locked\", a storage read that failed) is a `KEY_PROVIDER_FAILED` error with the\n * original error as `cause`: nothing has been sent, so `classifyFailure` says `not_sent` and Retry\n * is safe, and the app needs no error class of its own to tell this apart. A provider that returns\n * no usable string (`''`, `undefined`) is `INVALID_PRIVATE_KEY` with `reason: 'no_key_provided'`,\n * classified the same way; any other key that is not a valid secp256k1 key string is an\n * `INVALID_PRIVATE_KEY` error. An SDK error the provider throws itself is passed through.\n * Signatures are byte-identical to `new PrivateKeySigner(key).signObject(...)`.\n *\n * A JavaScript string cannot be wiped; the provider owns the lifetime of the string it returns.\n *\n * @example\n * ```typescript\n * const signer = createLazyPrivateKeySigner(\n * () => SecurityHelper.getSessionSecret(SecurityHelper.SESSION_PRIVATE_KEY_KEY),\n * { expectedAddress: account.address },\n * );\n * const gswap = new GSwap({ signer });\n * ```\n */\nexport function createLazyPrivateKeySigner(\n getPrivateKey: PrivateKeyProvider,\n options: LazyPrivateKeySignerOptions = {},\n): GalaChainSigner {\n const expected = options.expectedAddress;\n const expectedLower =\n expected === undefined\n ? undefined\n : normalizeEthereumAccount(expected, true, 'expectedAddress').toLowerCase();\n\n return {\n async signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const provided: unknown = await keyFrom(getPrivateKey);\n if (typeof provided !== 'string' || provided === '') {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'no_key_provided' });\n }\n const key = normalizePrivateKey(provided);\n try {\n if (expectedLower !== undefined && ethAddressOfPrivateKey(key) !== expectedLower) {\n throw new GalaSDKError('SIGNER_ADDRESS_MISMATCH', {});\n }\n return { ...dto, signature: signNative(key, dto) };\n } finally {\n key.fill(0);\n }\n },\n };\n}\n\n/**\n * A Gala Wallet signer using native GalaChain signing, with an opt-in personal-sign mode.\n *\n * The selected Ethereum account is passed to Gala Wallet. There is NO automatic fallback: a\n * wallet that rejects `native` surfaces its error to the caller, because the only alternative,\n * `personal-sign`, silently recovers a phantom signer on every released Gala Wallet.\n *\n * `scheme: 'personal-sign'` calls\n * `gala_signChainDto([serialize({ ...dto, prefix }), walletAddress, methodName])` and REQUIRES\n * a Gala Wallet build that strips the embedded `prefix` field and hashes `prefix` + the\n * prefix-less canonical body (the chain's scheme). Wallet builds that predate that fix hash the\n * string with the `prefix` field still inside it and the signature recovers to an address\n * nobody holds, so only opt in once the wallet you target has the fix.\n */\nexport class GalaWalletSigner implements GalaChainSigner {\n /** The wallet address supplied to Gala Wallet for each signing request. */\n public readonly walletAddress: string;\n\n /** The signing scheme used for every request; it never changes after construction. */\n public readonly scheme: GalaWalletScheme;\n\n /**\n * Creates a Gala Wallet signer.\n *\n * @example\n * ```typescript\n * const signer = new GalaWalletSigner('0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n *\n * @param walletAddress - The account passed to Gala Wallet as the signer address. An Ethereum\n * account is `0x` plus 40 hex digits (Gala Wallet's `eth|...` form is normalized to it and held\n * to the same check); a GalaChain id is `client|` plus 24 hex digits, or the bare 24 hex digits\n * a web app keeps for a direct `client|` login, and is passed through unchanged.\n * @param options - Select native signing (default) or personal-sign explicitly.\n * `'personal-sign'` requires a Gala Wallet build that signs the bare serialized DTO.\n * `selectAddress` is the identity (`client|...` / `eth|...`) Gala Wallet is switched to with\n * `setAddress` before every signature, when the wallet offers it. `wallet` is the Gala Wallet\n * object to sign through (the one an EIP-6963 announcement or a wallet provider holds); without\n * it, `window.gala` is read at every signature.\n */\n constructor(\n walletAddress: string,\n options: {\n scheme?: GalaWalletScheme | undefined;\n selectAddress?: string | undefined;\n wallet?: GalaWalletApi | undefined;\n } = {},\n ) {\n this.walletAddress = normalizeGalaWalletAccount(walletAddress);\n this.scheme = options.scheme ?? 'native';\n if (options.selectAddress !== undefined) assertWalletIdentity(options.selectAddress);\n this.selectAddress = options.selectAddress;\n this.wallet = options.wallet;\n }\n\n /** The identity Gala Wallet is switched to before each signature, if one was given. */\n public readonly selectAddress: string | undefined;\n\n /** The Gala Wallet object this signer signs through; `undefined` reads `window.gala` each time. */\n private readonly wallet: GalaWalletApi | undefined;\n\n /**\n * Signs a DTO through `gala_signChainDto`.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('AddLiquidity', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * tickLower: -60,\n * tickUpper: 60,\n * });\n * ```\n */\n public async signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const wallet = this.wallet ?? getWalletProvider();\n\n return withGalaWalletIdentity(wallet, this.selectAddress, async () => {\n if (this.scheme === 'personal-sign') {\n return personalSign(wallet, dto, this.walletAddress, methodName);\n }\n const signature = await wallet.request({\n method: 'gala_signChainDto',\n params: [serialize(dto), this.walletAddress, methodName, 'native'],\n });\n return { ...dto, signature: getNativeSignature(signature) };\n });\n }\n}\n\n/**\n * A personal-sign signer for MetaMask and other EIP-1193 browser wallets.\n *\n * The chain recovers this signature using the EIP-191 wrap applied by the wallet to\n * `personal_sign`. This is the browser-wallet path used by the v2 frontend and resolves the\n * bare `eth|` identity.\n */\nexport class BrowserWalletSigner implements GalaChainSigner {\n /**\n * Creates a browser-wallet signer.\n *\n * Defaults to `personal_sign` — unchanged from every existing integration, since it only ever\n * resolves the bare `eth|` identity and changing that silently would be a real behavior\n * break for anyone already depending on it. Pass `{ scheme: 'eip712' }` to correctly resolve\n * a registered `client|` alias instead, for `RequestTrade`/`AddLiquidity`/`RemoveLiquidity`/\n * `CollectPositionFees` (`EIP712_CAPABLE_METHODS`) — `CreatePool` and any other method still\n * falls back to `personal_sign` even in `'eip712'` mode, since its EIP-712 signing is a\n * separate, unsolved chain-side problem.\n *\n * @example\n * ```typescript\n * const signer = new BrowserWalletSigner(window.ethereum, '0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n * @example\n * ```typescript\n * // Correctly resolves a registered client| alias instead of the bare eth| address.\n * const signer = new BrowserWalletSigner(window.ethereum, walletAddress, { scheme: 'eip712' });\n * ```\n */\n constructor(\n private readonly provider: BrowserWalletProvider,\n walletAddress: string,\n options: { scheme?: 'personal-sign' | 'eip712' } = {},\n ) {\n this.walletAddress = normalizeEthereumAccount(walletAddress, false);\n this.scheme = options.scheme ?? 'personal-sign';\n }\n\n /** The selected `0x` Ethereum account every signature is requested for. */\n public readonly walletAddress: string;\n private readonly scheme: 'personal-sign' | 'eip712';\n\n /**\n * Signs the DTO with `eth_signTypedData_v4` (when constructed with `{ scheme: 'eip712' }` and\n * `methodName` is in `EIP712_CAPABLE_METHODS`) or the EIP-1193 `personal_sign` method\n * (otherwise — the default).\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n if (this.scheme === 'eip712' && EIP712_CAPABLE_METHODS.has(methodName)) {\n return signEIP712(this.provider, methodName, dto, this.walletA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W,EAAyBsB,EAAe,EAAK,EAClE,KAAK,OAASsB,EAAQ,QAAU,eAClC,CAoBA,WACE,EACA,EACuB,CAIvB,OAHI,KAAK,SAAW,UAAYO,EAAuB,IAAI/B,CAAU,EAC5DI,EAAW,KAAK,SAAUJ,EAAYH,EAAK,KAAK,aAAa,EAE/DH,EAAa,KAAK,SAAUG,EAAK,KAAK,aAAa,CAC5D,CACF,E"}
1
+ {"version":3,"file":"signers.js","names":["globalObject","_defineProperty","getWalletProvider","wallet","GalaSDKError","getNativeSignature","value","getPersonalSignature","ethereumAddressOfAccount","assertNoEthZeroXPrefix","account","match","normalizeEthereumAccount","address","field","normalized","allowGalaPrefix","normalizeGalaWalletAccount","eth","assertWalletIdentity","identity","walletIdentityQueue","withGalaWalletIdentity","setAddress","signWith","run","personalSign","prefix","personalSignPrefixFor","dto","payload","params","methodName","serialize","walletAddress","provider","signEIP712","buildEIP712Payload","domain","eip712DomainFor","domainName","fixpointPrefixFor","completedDto","message","eip712Domain","types","PrivateKeySigner","normalizePrivateKey","privateKey","signature","signNative","keyFrom","getPrivateKey","cause","isGalaError","createLazyPrivateKeySigner","expected","options","expectedLower","provided","key","ethAddressOfPrivateKey","GalaWalletSigner","BrowserWalletSigner","EIP712_CAPABLE_METHODS"],"sources":["../../../src/classes/signers.ts"],"sourcesContent":["import { GalaSDKError, isGalaError } from './gala_sdk_error.js';\nimport { assertNoEthZeroXPrefix } from '../writes/identity.js';\nimport {\n buildEIP712Payload,\n EIP712_CAPABLE_METHODS,\n eip712DomainFor,\n type EIP712DomainValue,\n type EIP712Types,\n} from '../utils/eip712.js';\nimport {\n ethAddressOfPrivateKey,\n fixpointPrefixFor,\n normalizePrivateKey,\n personalSignPrefixFor,\n serialize,\n signNative,\n} from '../utils/signing.js';\n\n// Personal-sign prefix, computed the way THE CHAIN verifies it.\n//\n// GalaChain (SDK 3.x) recovers a personal-signed DTO from\n// keccak256(<prefix field> + <canonical JSON of the DTO WITHOUT the prefix field>)\n// and a browser wallet's `personal_sign` (EIP-191) hashes\n// \"\\u0019Ethereum Signed Message:\\n\" + <byte length of message> + <message>.\n// They agree exactly when the wallet signs the bare canonical DTO and `prefix` is the EIP-191\n// header for that message's UTF-8 BYTE length. Any other message still yields a valid-looking\n// signature — it just recovers to an address nobody holds. This SDK used to embed `prefix` in\n// the signed message (the SDK 1.10 client recipe): observed on stage 2026-09-23, such a\n// MetaMask-signed CreatePool executed on chain under a phantom creator, and the swap backend's\n// write guard now rejects that shape outright.\n//\n// `@gala-chain/connect`'s prefix helper must NOT be used for wallet `personal_sign`: its\n// fixpoint counts the prefix itself and targets the SDK's raw-payload signer. The same header\n// is also what Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepends before hashing,\n// so one value serves both paths.\n//\n// The header itself is computed by `personalSignPrefixFor` in ../utils/signing.ts.\n\n/** The signing schemes supported by the Gala Wallet signer. */\nexport type GalaWalletScheme = 'native' | 'personal-sign';\n\n/** The request surface used by an EIP-1193 browser wallet. */\nexport interface BrowserWalletProvider {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n}\n\n/** The Gala Wallet extension's API (`window.gala`, or the same object from an EIP-6963 announcement). */\nexport interface GalaWalletApi {\n request(args: { method: string; params?: unknown[] }): Promise<unknown>;\n /** Gala Wallet's \"act as this account\" switch; absent on other providers. */\n setAddress?: (address: string) => Promise<void>;\n}\n\ninterface WindowWithGala {\n gala?: GalaWalletApi;\n}\n\ninterface GlobalWithWindow {\n window?: WindowWithGala;\n}\n\n/** A DTO together with the signature that belongs in the gateway request body. */\nexport type SignedDto<T extends Record<string, unknown>> = T & { signature: string };\n\n/**\n * A signer for complete GalaChain write bodies.\n *\n * Implementations return the DTO fields together with the signature that belongs in the\n * gateway request body. Signer identity is recovered from that signature; implementations do\n * not add signer hints, typed-data metadata, or a domain.\n */\nexport interface GalaChainSigner {\n /**\n * Signs a DTO for a named GalaChain contract method.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n signObject<T extends Record<string, unknown>>(methodName: string, dto: T): Promise<SignedDto<T>>;\n}\n\nfunction getWalletProvider(): GalaWalletApi {\n const globalObject = globalThis as GlobalWithWindow;\n const wallet = globalObject.window?.gala;\n if (!wallet) {\n throw new GalaSDKError('GALA_WALLET_NOT_AVAILABLE', {});\n }\n return wallet;\n}\n\nfunction getNativeSignature(value: unknown): string {\n if (typeof value !== 'string') {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n // 130 hex digits (r || s || v), bare as Gala Wallet returns it or `0x`-prefixed; passed on\n // verbatim, because the backend recovers the signer from either spelling.\n if (!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'native' });\n }\n return value;\n}\n\nfunction getPersonalSignature(value: unknown): string {\n if (typeof value !== 'string' || !/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {\n throw new GalaSDKError('INVALID_SIGNATURE', { scheme: 'personal-sign' });\n }\n return value;\n}\n\n/**\n * The `0x`-prefixed Ethereum address a Gala account is signed by, or `undefined` when the account\n * names no key (a `client|` alias or a bare GalaChain id is not derivable from a key). Accepts\n * `0x` plus 40 hex digits and `eth|` plus 40 hex digits; the caller's casing is kept. `eth|0x...`\n * is not an address form and is refused. For {@link LazyPrivateKeySignerOptions.expectedAddress}, which should only be set for\n * an account whose key can be checked.\n *\n * @example\n * ```ts\n * createLazyPrivateKeySigner(getKey, { expectedAddress: ethereumAddressOfAccount(account) });\n * ```\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` for `eth|0x...` (refused, never read as\n * \"names no key\", which would switch a signer's address check off).\n */\nexport function ethereumAddressOfAccount(account: string): string | undefined {\n assertNoEthZeroXPrefix(account, 'account');\n const match = /^(?:eth\\||0x)([0-9a-fA-F]{40})$/u.exec(account);\n return match?.[1] === undefined ? undefined : `0x${match[1]}`;\n}\n\nfunction normalizeEthereumAccount(\n address: string,\n allowGalaPrefix: boolean,\n field = 'walletAddress',\n): string {\n assertNoEthZeroXPrefix(address, field);\n const normalized = allowGalaPrefix ? (ethereumAddressOfAccount(address) ?? address) : address;\n if (!/^0x[0-9a-fA-F]{40}$/u.test(normalized)) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field, value: address });\n }\n // The caller's casing is kept on purpose: the Gala web apps and the wallet hand the wallet the\n // checksummed account, and EIP-1193 / Gala Wallet accept any case, so passing the value through\n // unchanged is the only choice that cannot differ from what they send.\n return normalized;\n}\n\n/**\n * The account handed to Gala Wallet as the signer address. An Ethereum account is held to the\n * same strict check as ever (`0x` plus 40 hex digits; `eth|` plus 40 hex digits is normalized to\n * it; `eth|0x...` is refused). A GalaChain id the wallet can also be asked to sign for is passed\n * through verbatim: `client|` plus 24 hex digits, or the bare 24 hex digits that a web app keeps\n * after a direct `client|` login. Nothing else is accepted.\n */\nfunction normalizeGalaWalletAccount(address: string): string {\n assertNoEthZeroXPrefix(address, 'walletAddress');\n const eth = /^eth\\|([0-9a-fA-F]{40})$/u.exec(address);\n if (eth?.[1] !== undefined) return `0x${eth[1]}`;\n if (/^0x[0-9a-fA-F]{40}$/u.test(address) || /^(?:client\\|)?[0-9a-fA-F]{24}$/u.test(address)) {\n return address;\n }\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field: 'walletAddress', value: address });\n}\n\n/** An identity Gala Wallet can act as: an account form above, any `eth|`/`client|` alias, verbatim. */\nfunction assertWalletIdentity(identity: string): void {\n assertNoEthZeroXPrefix(identity, 'selectAddress');\n if (\n !/^(?:eth\\|[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\\|)?[0-9a-fA-F]{24})$/u.test(identity)\n ) {\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field: 'selectAddress', value: identity });\n }\n}\n\n/** Provider-wide queue: `setAddress` + the signature request must not interleave across signers. */\nconst walletIdentityQueue = new WeakMap<object, Promise<unknown>>();\n\n/**\n * Runs `signWith` with `identity` selected on a Gala Wallet that supports `setAddress`. Gala\n * Wallet holds ONE current account, so two signatures for different identities in flight at once\n * would sign as whichever selection came last; the pair (select, sign) is therefore serialized\n * per wallet object, across every signer and provider that signs through it\n * (`GalaWalletSigner`, `./providers`' `GalaWalletProvider`). A failed selection fails the\n * signature (nothing is requested). Without an identity, or on a wallet without `setAddress`, it\n * just runs `signWith`.\n *\n * @example\n * ```typescript\n * const signature = await withGalaWalletIdentity(window.gala, 'eth|70997970C51812dc3A010C7d01b50e0d17dc79C8', () =>\n * window.gala.request({ method: 'personal_sign', params: [hexMessage, address] }),\n * );\n * ```\n */\nexport function withGalaWalletIdentity<T>(\n wallet: GalaWalletApi,\n identity: string | undefined,\n signWith: () => Promise<T>,\n): Promise<T> {\n const { setAddress } = wallet;\n if (identity === undefined || typeof setAddress !== 'function') return signWith();\n const previous = walletIdentityQueue.get(wallet) ?? Promise.resolve();\n const run = previous\n .catch(() => undefined)\n .then(async () => {\n await setAddress.call(wallet, identity);\n return signWith();\n });\n walletIdentityQueue.set(wallet, run);\n return run;\n}\n\nfunction personalSign<T extends Record<string, unknown>>(\n provider: GalaWalletApi | BrowserWalletProvider,\n dto: T,\n walletAddress: string,\n methodName?: string,\n): Promise<T & { prefix: string; signature: string }> {\n const prefix = personalSignPrefixFor(dto);\n const payload = { ...dto, prefix };\n // A browser wallet's `personal_sign` applies the EIP-191 header ITSELF, so it must sign the\n // bare DTO; Gala Wallet's `gala_signChainDto` (personal-sign scheme) instead extracts the\n // `prefix` field from what it is handed and prepends it before hashing, so it is handed the\n // prefixed payload. Both submit `{ ...dto, prefix, signature }`.\n const params =\n methodName !== undefined\n ? [serialize(payload), walletAddress, methodName]\n : [serialize(dto), walletAddress];\n\n return provider\n .request({ method: methodName !== undefined ? 'gala_signChainDto' : 'personal_sign', params })\n .then((value) => ({ ...payload, signature: getPersonalSignature(value) }));\n}\n\n/**\n * Signs a DTO via genuine EIP-712 (`eth_signTypedData_v4`) — correctly resolves the `client|`\n * identity, unlike `personal_sign`, for the operations in `EIP712_CAPABLE_METHODS`.\n *\n * Constructs the raw JSON-RPC payload by hand (`{domain, types: {...types, EIP712Domain},\n * primaryType, message}`) rather than depending on ethers.js, matching exactly what\n * `ethers.TypedDataEncoder.getPayload`/`Wallet.signTypedData` produce internally — verified\n * byte-for-byte equivalent (same recovered address from the same signature against both\n * constructions) before this shipped, since the core SDK deliberately has no ethers dependency.\n */\nasync function signEIP712<T extends Record<string, unknown>>(\n provider: BrowserWalletProvider,\n methodName: string,\n dto: T,\n walletAddress: string,\n domainName?: string,\n): Promise<T & { types: EIP712Types; domain: EIP712DomainValue; signature: string }> {\n const { completedDto, types } = buildEIP712Payload(methodName, dto);\n // The wallet's LIVE chain id, read on every signature: a user can switch networks after\n // connecting, and a cached or hardcoded id would sign a domain MetaMask itself rejects. The\n // name is the deployment's (`eip712DomainName`), `ethereum` when none is given.\n const domain = eip712DomainFor(\n await provider.request({ method: 'eth_chainId', params: [] }),\n domainName,\n );\n // The body `prefix` is not part of the EIP-712 `types`, so it is never hashed; it carries the\n // connect-style fixpoint value only to keep the submitted body byte-identical to what the Gala\n // web apps have always sent.\n const prefix = fixpointPrefixFor(completedDto);\n const message = { ...completedDto, prefix };\n const eip712Domain = [\n { name: 'name', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n ];\n const payload = {\n domain,\n types: { ...types, EIP712Domain: eip712Domain },\n primaryType: methodName,\n message,\n };\n\n const value = await provider.request({\n method: 'eth_signTypedData_v4',\n params: [walletAddress, JSON.stringify(payload)],\n });\n // Key order matches the body the Gala web apps submit: ..., prefix, signature, types, domain.\n return {\n ...(message as T & { prefix: string }),\n signature: getPersonalSignature(value),\n types,\n domain,\n };\n}\n\n/**\n * A GalaChain native signer backed by a secp256k1 private key.\n *\n * Native signing produces the bare GalaChain signature format, without a personal-sign prefix\n * or EIP-712 metadata. The private-key identity is recovered by the chain.\n */\nexport class PrivateKeySigner implements GalaChainSigner {\n private readonly privateKey: Uint8Array;\n\n /**\n * Creates a native signer from a hex or base64 secp256k1 private key.\n *\n * @example\n * ```typescript\n * const signer = new PrivateKeySigner('1'.padStart(64, '0'));\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n */\n constructor(privateKey: string) {\n this.privateKey = normalizePrivateKey(privateKey);\n }\n\n /**\n * Signs the DTO with GalaChain native signing.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const signature = signNative(this.privateKey, dto);\n return Promise.resolve({ ...dto, signature });\n }\n}\n\n/** Supplies a private key at sign time: a hex/base64 string, possibly fetched asynchronously. */\nexport type PrivateKeyProvider = () => Promise<string> | string;\n\n/** Options for {@link createLazyPrivateKeySigner}. */\nexport interface LazyPrivateKeySignerOptions {\n /**\n * When set, every signature first checks that the fetched key belongs to this account (`0x...`\n * or the Gala `eth|<40 hex>` form, case-insensitive; `eth|0x...` is refused at creation) and\n * refuses to sign otherwise (`SIGNER_ADDRESS_MISMATCH`). Use it when the key lives in a slot another surface can switch\n * between the moment a request was approved and the moment it is signed.\n */\n expectedAddress?: string | undefined;\n}\n\n/**\n * Calls the app's key provider. Whatever it throws or rejects with is the app's own failure to\n * produce a key before anything was signed or sent, so it becomes `KEY_PROVIDER_FAILED` (the\n * original is `cause`); an SDK error is already catalogued and passes through.\n */\nasync function keyFrom(getPrivateKey: PrivateKeyProvider): Promise<unknown> {\n try {\n return await getPrivateKey();\n } catch (cause: unknown) {\n throw isGalaError(cause) ? cause : new GalaSDKError('KEY_PROVIDER_FAILED', {}, { cause });\n }\n}\n\n/**\n * Creates the native-signing equivalent of {@link PrivateKeySigner} for apps that must not hold a\n * key in a long-lived object (an extension that reads its session key at sign time).\n *\n * `getPrivateKey` is called once per `signObject` call, never cached, never shared between calls\n * (concurrent signatures each fetch their own key), and the normalized key bytes are zeroed\n * before `signObject` settles, also on failure. A rejection or exception from `getPrivateKey` (the\n * app's \"wallet is locked\", a storage read that failed) is a `KEY_PROVIDER_FAILED` error with the\n * original error as `cause`: nothing has been sent, so `classifyFailure` says `not_sent` and Retry\n * is safe, and the app needs no error class of its own to tell this apart. A provider that returns\n * no usable string (`''`, `undefined`) is `INVALID_PRIVATE_KEY` with `reason: 'no_key_provided'`,\n * classified the same way; any other key that is not a valid secp256k1 key string is an\n * `INVALID_PRIVATE_KEY` error. An SDK error the provider throws itself is passed through.\n * Signatures are byte-identical to `new PrivateKeySigner(key).signObject(...)`.\n *\n * A JavaScript string cannot be wiped; the provider owns the lifetime of the string it returns.\n *\n * @example\n * ```typescript\n * const signer = createLazyPrivateKeySigner(\n * () => SecurityHelper.getSessionSecret(SecurityHelper.SESSION_PRIVATE_KEY_KEY),\n * { expectedAddress: account.address },\n * );\n * const gswap = new GSwap({ signer });\n * ```\n */\nexport function createLazyPrivateKeySigner(\n getPrivateKey: PrivateKeyProvider,\n options: LazyPrivateKeySignerOptions = {},\n): GalaChainSigner {\n const expected = options.expectedAddress;\n const expectedLower =\n expected === undefined\n ? undefined\n : normalizeEthereumAccount(expected, true, 'expectedAddress').toLowerCase();\n\n return {\n async signObject<T extends Record<string, unknown>>(\n _methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const provided: unknown = await keyFrom(getPrivateKey);\n if (typeof provided !== 'string' || provided === '') {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'no_key_provided' });\n }\n const key = normalizePrivateKey(provided);\n try {\n if (expectedLower !== undefined && ethAddressOfPrivateKey(key) !== expectedLower) {\n throw new GalaSDKError('SIGNER_ADDRESS_MISMATCH', {});\n }\n return { ...dto, signature: signNative(key, dto) };\n } finally {\n key.fill(0);\n }\n },\n };\n}\n\n/**\n * A Gala Wallet signer using native GalaChain signing, with an opt-in personal-sign mode.\n *\n * The selected Ethereum account is passed to Gala Wallet. There is NO automatic fallback: a\n * wallet that rejects `native` surfaces its error to the caller, because the only alternative,\n * `personal-sign`, silently recovers a phantom signer on every released Gala Wallet.\n *\n * `scheme: 'personal-sign'` calls\n * `gala_signChainDto([serialize({ ...dto, prefix }), walletAddress, methodName])` and REQUIRES\n * a Gala Wallet build that strips the embedded `prefix` field and hashes `prefix` + the\n * prefix-less canonical body (the chain's scheme). Wallet builds that predate that fix hash the\n * string with the `prefix` field still inside it and the signature recovers to an address\n * nobody holds, so only opt in once the wallet you target has the fix.\n */\nexport class GalaWalletSigner implements GalaChainSigner {\n /** The wallet address supplied to Gala Wallet for each signing request. */\n public readonly walletAddress: string;\n\n /** The signing scheme used for every request; it never changes after construction. */\n public readonly scheme: GalaWalletScheme;\n\n /**\n * Creates a Gala Wallet signer.\n *\n * @example\n * ```typescript\n * const signer = new GalaWalletSigner('0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n *\n * @param walletAddress - The account passed to Gala Wallet as the signer address. An Ethereum\n * account is `0x` plus 40 hex digits (Gala Wallet's `eth|...` form is normalized to it and held\n * to the same check); a GalaChain id is `client|` plus 24 hex digits, or the bare 24 hex digits\n * a web app keeps for a direct `client|` login, and is passed through unchanged.\n * @param options - Select native signing (default) or personal-sign explicitly.\n * `'personal-sign'` requires a Gala Wallet build that signs the bare serialized DTO.\n * `selectAddress` is the identity (`client|...` / `eth|...`) Gala Wallet is switched to with\n * `setAddress` before every signature, when the wallet offers it. `wallet` is the Gala Wallet\n * object to sign through (the one an EIP-6963 announcement or a wallet provider holds); without\n * it, `window.gala` is read at every signature.\n */\n constructor(\n walletAddress: string,\n options: {\n scheme?: GalaWalletScheme | undefined;\n selectAddress?: string | undefined;\n wallet?: GalaWalletApi | undefined;\n } = {},\n ) {\n this.walletAddress = normalizeGalaWalletAccount(walletAddress);\n this.scheme = options.scheme ?? 'native';\n if (options.selectAddress !== undefined) assertWalletIdentity(options.selectAddress);\n this.selectAddress = options.selectAddress;\n this.wallet = options.wallet;\n }\n\n /** The identity Gala Wallet is switched to before each signature, if one was given. */\n public readonly selectAddress: string | undefined;\n\n /** The Gala Wallet object this signer signs through; `undefined` reads `window.gala` each time. */\n private readonly wallet: GalaWalletApi | undefined;\n\n /**\n * Signs a DTO through `gala_signChainDto`.\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('AddLiquidity', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * tickLower: -60,\n * tickUpper: 60,\n * });\n * ```\n */\n public async signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n const wallet = this.wallet ?? getWalletProvider();\n\n return withGalaWalletIdentity(wallet, this.selectAddress, async () => {\n if (this.scheme === 'personal-sign') {\n return personalSign(wallet, dto, this.walletAddress, methodName);\n }\n const signature = await wallet.request({\n method: 'gala_signChainDto',\n params: [serialize(dto), this.walletAddress, methodName, 'native'],\n });\n return { ...dto, signature: getNativeSignature(signature) };\n });\n }\n}\n\n/**\n * A personal-sign signer for MetaMask and other EIP-1193 browser wallets.\n *\n * The chain recovers this signature using the EIP-191 wrap applied by the wallet to\n * `personal_sign`. This is the browser-wallet path used by the v2 frontend and resolves the\n * bare `eth|` identity.\n */\nexport class BrowserWalletSigner implements GalaChainSigner {\n /**\n * Creates a browser-wallet signer.\n *\n * Defaults to `personal_sign` — unchanged from every existing integration, since it only ever\n * resolves the bare `eth|` identity and changing that silently would be a real behavior\n * break for anyone already depending on it. Pass `{ scheme: 'eip712' }` to correctly resolve\n * a registered `client|` alias instead, for `RequestTrade`/`AddLiquidity`/`RemoveLiquidity`/\n * `CollectPositionFees` (`EIP712_CAPABLE_METHODS`) — `CreatePool` and any other method still\n * falls back to `personal_sign` even in `'eip712'` mode, since its EIP-712 signing is a\n * separate, unsolved chain-side problem.\n *\n * `eip712DomainName` is the EIP-712 domain name every typed-data signature carries (the\n * `'eip712'` scheme only; `personal_sign` has no domain): the deployment's own\n * (`GALA_CHAIN_ENVIRONMENTS[env].eip712DomainName`), `ethereum` when absent.\n *\n * @example\n * ```typescript\n * const signer = new BrowserWalletSigner(window.ethereum, '0x0123456789012345678901234567890123456789');\n * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });\n * ```\n * @example\n * ```typescript\n * // Correctly resolves a registered client| alias instead of the bare eth| address.\n * const signer = new BrowserWalletSigner(window.ethereum, walletAddress, { scheme: 'eip712' });\n * ```\n * @example\n * ```typescript\n * // The stage chain refuses any EIP-712 domain name but its own.\n * const signer = new BrowserWalletSigner(window.ethereum, walletAddress, {\n * scheme: 'eip712',\n * eip712DomainName: GALA_CHAIN_ENVIRONMENTS.stage.eip712DomainName,\n * });\n * ```\n */\n constructor(\n private readonly provider: BrowserWalletProvider,\n walletAddress: string,\n options: { scheme?: 'personal-sign' | 'eip712'; eip712DomainName?: string | undefined } = {},\n ) {\n this.walletAddress = normalizeEthereumAccount(walletAddress, false);\n this.scheme = options.scheme ?? 'personal-sign';\n this.eip712DomainName = options.eip712DomainName;\n }\n\n /** The selected `0x` Ethereum account every signature is requested for. */\n public readonly walletAddress: string;\n private readonly scheme: 'personal-sign' | 'eip712';\n private readonly eip712DomainName: string | undefined;\n\n /**\n * Signs the DTO with `eth_signTypedData_v4` (when constructed with `{ scheme: 'eip712' }` and\n * `methodName` is in `EIP712_CAPABLE_METHODS`) or the EIP-1193 `personal_sign` method\n * (otherwise — the default).\n *\n * @example\n * ```typescript\n * const signed = await signer.signObject('RequestTrade', {\n * token0: 'GALA',\n * token1: 'GUSDC',\n * fee: 3000,\n * });\n * ```\n */\n public signObject<T extends Record<string, unknown>>(\n methodName: string,\n dto: T,\n ): Promise<SignedDto<T>> {\n if (this.scheme === 'eip712' && EIP712_CAPABLE_METHODS.has(methodName)) {\n return signEIP712(this.provider, methodName, dto, this.walletAddress, this.eip712DomainName);\n }\n return personalSign(this.provider, dto, this.walletAddress);\n }\n}\n"],"mappings":"A,0eAmFA,SAASE,GAAmC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,KAAK,OAASuB,EAAQ,QAAU,gBAChC,KAAK,iBAAmBA,EAAQ,gBAClC,CAqBA,WACE,EACA,EACuB,CAIvB,OAHI,KAAK,SAAW,UAAYO,EAAuB,IAAIhC,CAAU,EAC5DI,EAAW,KAAK,SAAUJ,EAAYH,EAAK,KAAK,cAAe,KAAK,gBAAgB,EAEtFH,EAAa,KAAK,SAAUG,EAAK,KAAK,aAAa,CAC5D,CACF,E"}
@@ -1,2 +1,2 @@
1
- const e=Object.freeze({prod:Object.freeze({gatewayBaseUrl:`https://gateway-mainnet.galachain.com`,dexApiBaseUrl:`https://dex-api-platform-dex-prod-gala.gala.com`}),stage:Object.freeze({gatewayBaseUrl:`https://gateway-testnet.galachain.com`,dexApiBaseUrl:`https://dex-api-platform-dex-stage-gala.gala.com`})});export{e as GALA_CHAIN_ENVIRONMENTS};
1
+ const e=Object.freeze({prod:Object.freeze({gatewayBaseUrl:`https://gateway-mainnet.galachain.com`,dexApiBaseUrl:`https://dex-api-platform-dex-prod-gala.gala.com`}),stage:Object.freeze({gatewayBaseUrl:`https://gateway-testnet.galachain.com`,dexApiBaseUrl:`https://dex-api-platform-dex-stage-gala.gala.com`,eip712DomainName:`GalaChainStage`})});export{e as GALA_CHAIN_ENVIRONMENTS};
2
2
  //# sourceMappingURL=environments.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"environments.js","names":["GALA_CHAIN_ENVIRONMENTS"],"sources":["../../../src/config/environments.ts"],"sourcesContent":["/** A GalaChain deployment: `prod` (mainnet) or `stage` (testnet). */\nexport type GalaChainEnv = 'prod' | 'stage';\n\n/** The product-independent endpoints of one GalaChain deployment. */\nexport interface GalaChainEnvironmentConfig {\n /** The public GalaChain gateway (`GatewayReads` / `GatewayWrites` `gatewayBaseUrl`). */\n readonly gatewayBaseUrl: string;\n /** The DEX API platform (GalaConnect: bridge, wrap and referral reads). */\n readonly dexApiBaseUrl: string;\n}\n\n/**\n * The built-in endpoints of each deployment. A product SDK extends these with its own backends\n * (launchpad-sdk's launchpad and bundler URLs, gswap-sdk's swap backend); it never redefines them.\n */\nexport const GALA_CHAIN_ENVIRONMENTS: Readonly<Record<GalaChainEnv, GalaChainEnvironmentConfig>> =\n Object.freeze({\n prod: Object.freeze({\n gatewayBaseUrl: 'https://gateway-mainnet.galachain.com',\n dexApiBaseUrl: 'https://dex-api-platform-dex-prod-gala.gala.com',\n }),\n stage: Object.freeze({\n gatewayBaseUrl: 'https://gateway-testnet.galachain.com',\n dexApiBaseUrl: 'https://dex-api-platform-dex-stage-gala.gala.com',\n }),\n });\n"],"mappings":"AAeA,MAAaA,EACX,OAAO,OAAO,CACZ,KAAM,OAAO,OAAO,CAClB,eAAgB,wCAChB,cAAe,iDACjB,CAAC,EACD,MAAO,OAAO,OAAO,CACnB,eAAgB,wCAChB,cAAe,kDACjB,CAAC,CACH,CAAC,E"}
1
+ {"version":3,"file":"environments.js","names":["GALA_CHAIN_ENVIRONMENTS"],"sources":["../../../src/config/environments.ts"],"sourcesContent":["/** A GalaChain deployment: `prod` (mainnet) or `stage` (testnet). */\nexport type GalaChainEnv = 'prod' | 'stage';\n\n/** The product-independent endpoints of one GalaChain deployment. */\nexport interface GalaChainEnvironmentConfig {\n /** The public GalaChain gateway (`GatewayReads` / `GatewayWrites` `gatewayBaseUrl`). */\n readonly gatewayBaseUrl: string;\n /** The DEX API platform (GalaConnect: bridge, wrap and referral reads). */\n readonly dexApiBaseUrl: string;\n /**\n * The EIP-712 domain NAME the deployment's chain requires of a typed-data signature\n * (\"EIP-712 domain name must be GalaChainStage for this deployment. Received ethereum.\"). Pass\n * it to a signer's `eip712DomainName` option. Absent where the deployment accepts the name each\n * signer has always used (`prod`), so a signer given `undefined` signs exactly what it always\n * did.\n */\n readonly eip712DomainName?: string;\n}\n\n/**\n * The built-in endpoints of each deployment. A product SDK extends these with its own backends\n * (launchpad-sdk's launchpad and bundler URLs, gswap-sdk's swap backend); it never redefines them.\n */\nexport const GALA_CHAIN_ENVIRONMENTS: Readonly<Record<GalaChainEnv, GalaChainEnvironmentConfig>> =\n Object.freeze({\n prod: Object.freeze({\n gatewayBaseUrl: 'https://gateway-mainnet.galachain.com',\n dexApiBaseUrl: 'https://dex-api-platform-dex-prod-gala.gala.com',\n }),\n stage: Object.freeze({\n gatewayBaseUrl: 'https://gateway-testnet.galachain.com',\n dexApiBaseUrl: 'https://dex-api-platform-dex-stage-gala.gala.com',\n eip712DomainName: 'GalaChainStage',\n }),\n });\n"],"mappings":"AAuBA,MAAaA,EACX,OAAO,OAAO,CACZ,KAAM,OAAO,OAAO,CAClB,eAAgB,wCAChB,cAAe,iDACjB,CAAC,EACD,MAAO,OAAO,OAAO,CACnB,eAAgB,wCAChB,cAAe,mDACf,iBAAkB,gBACpB,CAAC,CACH,CAAC,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"providers.js","names":["textEncoder","eip712DomainType","fields","domain","serializeTypedDataDomain","result","\"name\"","\"version\"","\"chainId\"","\"verifyingContract\"","\"salt\"","buildTypedDataPayload","types","encodePersonalSignMessage","bytesToHex","message","signatureOf","value","GalaSDKError","requestPersonalSignature","wallet","address","requestTypedDataSignature","DISCONNECTED","isWalletDisconnection","code","walletFailure","isGalaError","error","context","walletDeclineCode","reason","isWalletUserRejection","operation","_typeof","o","toPrimitive","t","e","i","r","toPropertyKey","_defineProperty","notifyAccountListeners","listener","listeners","WalletConnection","args","accounts","raw","account","generation","version","checksumEthereumAddress","spelled","ExternalWalletProvider","provider","BrowserWalletSigner","options","SELECTABLE_IDENTITY","galaWalletCode","parsed","GalaWalletProvider","withGalaWalletIdentity","GalaWalletSigner","_checkPrivateRedeclaration","_classPrivateMethodInitSpec","a","_classPrivateFieldInitSpec","_assertClassBrand","_classPrivateFieldSet2","s","_classPrivateFieldGet2","KEY_SPELLING","hasUnpairedSurrogate","index","unit","next","presentDomain","signingFailure","_privateKey","_address","_connected","_listeners","_PrivateKeyProvider_brand","PrivateKeyProvider","privateKey","key","normalizePrivateKey","ethAddressOfPrivateKey","signPersonalMessage","calculatePersonalSignPrefix","signTypedDataPayload","PrivateKeySigner","_notify","KNOWN_WALLET_RDNS","DEFAULT_WALLET_ICONS","ANNOUNCE","TRUST_INITIALIZED","browserWindow","candidate","window","isRequestable","isString","announcement","detail","event","info","uuid","name","id","rdns","icon","requestAnnouncements","EventConstructor","injectedProvider","ethereum","trustWalletProvider","providers","found","camel","isMetaMaskProvider","isTrustProvider","injectedMetaMask","injectedWallet","injectedFallback","wallets","has","flags","metamask","trust","resultOf","detectWallets","seen","onAnnounce","announced","resolve","timeout","subscribeToWalletChanges","subscribed","current","known","callback","getWalletByRdns","isWalletAvailable","findMetaMaskWallet","findTrustWallet","getMetaMaskWallet","trustInitialized","done","timer","getTrustWallet","hasAnyWallet","getInjectedEip1193Provider","createWalletProvider","config","createProviderFromEip1193","isPrivateKeyProvider","isExternalProvider","getPrivateKeyIfAvailable","ensureConnected","isEip1193Provider"],"sources":["../../src/providers/wallet_requests.ts","../../src/providers/wallet_connection.ts","../../src/providers/external_wallet_provider.ts","../../src/providers/gala_wallet_provider.ts","../../src/providers/private_key_provider.ts","../../src/providers/detection.ts","../../src/providers/provider_utils.ts"],"sourcesContent":["/**\n * The requests a wallet-backed provider sends (`personal_sign`, `eth_signTypedData_v4`) and the one\n * mapping of what a wallet throws onto the core error codes. The bytes handed to a wallet are pinned\n * by launchpad-sdk's `wallet-providers.golden.json` (captured before the move from launchpad-sdk).\n */\nimport { bytesToHex } from '@noble/hashes/utils';\nimport {\n GalaSDKError,\n isGalaError,\n isWalletUserRejection,\n walletDeclineCode,\n type GalaErrorParamsShape,\n} from '../index.js';\nimport type { TypedDataDomain, TypedDataField } from './types.js';\n\n/** Any SDK error: core's, or a product SDK's subclass passed through as it is. */\nexport type SdkError = GalaSDKError<string, GalaErrorParamsShape>;\n\n/** The request surface of an EIP-1193 wallet (and of Gala Wallet). */\nexport interface WalletRequester {\n request<T = unknown>(args: { method: string; params?: unknown[] }): Promise<T>;\n}\n\nconst textEncoder = new TextEncoder();\n\nfunction eip712DomainType(domain: TypedDataDomain): TypedDataField[] {\n const fields: TypedDataField[] = [];\n if (domain.name !== undefined) fields.push({ name: 'name', type: 'string' });\n if (domain.version !== undefined) fields.push({ name: 'version', type: 'string' });\n if (domain.chainId !== undefined) fields.push({ name: 'chainId', type: 'uint256' });\n if (domain.verifyingContract !== undefined) {\n fields.push({ name: 'verifyingContract', type: 'address' });\n }\n if (domain.salt !== undefined) fields.push({ name: 'salt', type: 'bytes32' });\n return fields;\n}\n\n/** The domain as JSON-RPC carries it: a numeric chain id as `0x` hex, a string one as written. */\nfunction serializeTypedDataDomain(domain: TypedDataDomain): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n if (domain.name !== undefined) result['name'] = domain.name;\n if (domain.version !== undefined) result['version'] = domain.version;\n if (domain.chainId !== undefined) {\n result['chainId'] =\n typeof domain.chainId === 'string' ? domain.chainId : `0x${domain.chainId.toString(16)}`;\n }\n if (domain.verifyingContract !== undefined) {\n result['verifyingContract'] = domain.verifyingContract;\n }\n if (domain.salt !== undefined) result['salt'] = domain.salt;\n return result;\n}\n\n/**\n * The JSON-RPC `eth_signTypedData_v4` payload: `EIP712Domain` FIRST in `types`, the primary type\n * the first key of `types`, the domain serialized for JSON-RPC.\n *\n * @example\n * ```typescript\n * buildTypedDataPayload({ name: 'Launchpad' }, { Message: [{ name: 'value', type: 'string' }] }, { value: 'hi' });\n * ```\n */\nexport function buildTypedDataPayload(\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n message: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n types: { EIP712Domain: eip712DomainType(domain), ...types },\n primaryType: Object.keys(types)[0],\n domain: serializeTypedDataDomain(domain),\n message,\n };\n}\n\n/**\n * A message as `personal_sign` carries it: `0x` plus the hex of its UTF-8 bytes (a lone surrogate\n * is encoded as U+FFFD, as every UTF-8 encoder does).\n *\n * @example\n * ```typescript\n * encodePersonalSignMessage('hello'); // '0x68656c6c6f'\n * ```\n */\nexport function encodePersonalSignMessage(message: string): string {\n return `0x${bytesToHex(textEncoder.encode(message))}`;\n}\n\nfunction signatureOf(value: unknown, scheme: string): string {\n if (typeof value !== 'string') throw new GalaSDKError('INVALID_SIGNATURE', { scheme });\n return value;\n}\n\n/** Asks a wallet for a `personal_sign` signature of `message` by `address`. */\nexport async function requestPersonalSignature(\n wallet: WalletRequester,\n address: string,\n message: string,\n): Promise<string> {\n const signature = await wallet.request<unknown>({\n method: 'personal_sign',\n params: [encodePersonalSignMessage(message), address],\n });\n return signatureOf(signature, 'personal-sign');\n}\n\n/** Asks a wallet for an `eth_signTypedData_v4` signature by `address`. */\nexport async function requestTypedDataSignature(\n wallet: WalletRequester,\n address: string,\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n message: Record<string, unknown>,\n): Promise<string> {\n const signature = await wallet.request<unknown>({\n method: 'eth_signTypedData_v4',\n params: [address, JSON.stringify(buildTypedDataPayload(domain, types, message))],\n });\n return signatureOf(signature, 'typed-data');\n}\n\n/** EIP-1193 codes for \"the wallet does not let this app use the account\". */\nconst UNAUTHORIZED = 4100;\n/** EIP-1193 codes for \"the wallet is disconnected\" (from every chain, from this chain). */\nconst DISCONNECTED: readonly unknown[] = [4900, 4901];\n\n/** What the provider operation was, for the error a wallet failure becomes. */\nexport type WalletOperation = 'connect' | 'personal_sign' | 'eth_signTypedData_v4';\n\n/** True when a wallet failure says the wallet is disconnected (the provider must forget it). */\nexport function isWalletDisconnection(code: number | string | undefined): boolean {\n return DISCONNECTED.includes(code);\n}\n\n/**\n * The core error a wallet's failure becomes, from its code (`code`, already parsed out of the\n * wallet's error) and the operation: an SDK error passes through; `4100` is `WALLET_NOT_CONNECTED`\n * (`unauthorized`), `4900` / `4901` `WALLET_NOT_CONNECTED` (`disconnected`); a decline\n * (`isWalletUserRejection`) is `WALLET_CONNECTION_FAILED` / `SIGNING_FAILED` with `user_rejected`;\n * anything else `failed`. The wallet's error is `cause` and its code `walletCode`.\n */\nexport function walletFailure(\n error: unknown,\n code: number | string | undefined,\n operation: WalletOperation,\n): SdkError {\n if (isGalaError(error)) return error;\n const context = { cause: error, walletCode: code ?? walletDeclineCode(error) };\n if (code === UNAUTHORIZED) {\n return new GalaSDKError('WALLET_NOT_CONNECTED', { reason: 'unauthorized', operation }, context);\n }\n if (isWalletDisconnection(code)) {\n return new GalaSDKError('WALLET_NOT_CONNECTED', { reason: 'disconnected', operation }, context);\n }\n const reason = code === 4001 || isWalletUserRejection(error) ? 'user_rejected' : 'failed';\n return operation === 'connect'\n ? new GalaSDKError('WALLET_CONNECTION_FAILED', { reason }, context)\n : new GalaSDKError('SIGNING_FAILED', { method: operation, reason }, context);\n}\n","/**\n * The connection state every wallet-backed provider shares (`ExternalWalletProvider`,\n * `GalaWalletProvider`): the account it signs for, the wallet events that move it, and the\n * listeners that follow it.\n *\n * Invariants (each tested in tests/providers.test.ts):\n *\n * - The wallet's events are listened to ONLY while connected: `connect()` subscribes once,\n * `disconnect()` and every wallet-side disconnection unsubscribe. A provider that was never\n * connected, or was disconnected, holds no listener on the wallet (no leak) and an\n * `accountsChanged` cannot connect it behind the app's back.\n * - The account and the spelling the wallet reported for it (`raw`, what Gala Wallet's\n * `setAddress` is handed) change together, in one assignment: they can never describe two\n * different accounts.\n * - An operation reads the connection ONCE, before its first await, and uses that snapshot for\n * every request it makes: a switch mid-operation cannot make one request name the old account\n * and the next the new one.\n * - A `connect()` that finishes after a later `disconnect()` does not connect (generation check).\n * - A `restore()` (the silent reconnect: `eth_accounts` only) is stricter: its answer is applied\n * only if nothing moved the account while the wallet answered (no `disconnect()`, wallet event or\n * `connect()` in between), because `eth_accounts` can be older than any of them.\n * - A chain change does not move the account (the identity is chain-independent); nothing here\n * caches a chain id that a `chainChanged` could make stale: the EIP-712 signers read the chain at\n * each signature.\n */\nimport { GalaSDKError, checksumEthereumAddress } from '../index.js';\nimport type { Eip1193Provider } from './types.js';\nimport {\n isWalletDisconnection,\n walletFailure,\n type SdkError,\n type WalletOperation,\n} from './wallet_requests.js';\n\n/** The account a provider is connected to: checksummed, and as the wallet reported it. */\nexport interface WalletAccount {\n /** `0x` plus the EIP-55 digits. */\n readonly address: string;\n /** The account exactly as the wallet reported it (`eth|...`, `0x...`, bare hex). */\n readonly raw: string;\n}\n\n/** A listener of the connected account: the new address, or `null` once disconnected. */\nexport type AccountListener = (address: string | null) => void;\n\n/**\n * Calls every account listener. A listener that throws is the app's bug: it is reported\n * asynchronously (an unhandled error the app's handler sees) and never breaks the provider's\n * state or the other listeners.\n */\nexport function notifyAccountListeners(\n listeners: ReadonlySet<AccountListener>,\n address: string | null,\n): void {\n for (const listener of [...listeners]) {\n try {\n listener(address);\n } catch (error: unknown) {\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n}\n\n/**\n * The base of a wallet-backed provider. Subclasses say how the wallet spells an account\n * (`accountOf`) and read the wallet's code off its errors (`walletCodeOf`).\n */\nexport abstract class WalletConnection<W extends Eip1193Provider> {\n protected readonly wallet: W;\n private account: WalletAccount | null = null;\n private generation = 0;\n /** Moves with every change of the account (set, switched, forgotten): a `restore()` in flight compares it. */\n private version = 0;\n private listening = false;\n private readonly listeners = new Set<AccountListener>();\n\n private readonly onAccountsChanged = (...args: unknown[]): void => {\n const accounts = args[0];\n const raw = Array.isArray(accounts) ? (accounts[0] as unknown) : undefined;\n const account = typeof raw === 'string' ? this.accountOf(raw) : undefined;\n // No account (or one the wallet spells in a way that is not an account) is a disconnection.\n if (account === undefined) {\n this.forget();\n return;\n }\n this.account = account;\n this.version += 1;\n this.notify(account.address);\n };\n\n private readonly onWalletDisconnect = (): void => {\n this.forget();\n };\n\n protected constructor(wallet: W | null | undefined) {\n if (wallet === null || wallet === undefined) {\n throw new GalaSDKError('INVALID_WALLET_PROVIDER_CONFIG', { missing: 'eip1193_provider' });\n }\n this.wallet = wallet;\n }\n\n /** The account `raw` names, or `undefined` when it does not name one. */\n protected abstract accountOf(raw: string): WalletAccount | undefined;\n\n /** The wallet's code on its error (an EIP-1193 number), when it carries one. */\n protected abstract walletCodeOf(error: unknown): number | string | undefined;\n\n /**\n * Asks the wallet for account access (`eth_requestAccounts`) and listens to its account and\n * disconnect events from then on.\n *\n * @returns The connected account (`0x`, checksummed).\n * @throws GalaSDKError `WALLET_CONNECTION_FAILED` (`no_accounts`, `user_rejected`, `failed`),\n * `WALLET_NOT_CONNECTED` (the wallet refused or is disconnected, or `disconnect()` was called\n * before the wallet answered).\n */\n public async connect(): Promise<string> {\n const generation = this.generation;\n let accounts: unknown;\n try {\n accounts = await this.wallet.request<unknown>({ method: 'eth_requestAccounts' });\n } catch (error: unknown) {\n throw this.failure(error, 'connect');\n }\n if (generation !== this.generation) {\n throw new GalaSDKError('WALLET_NOT_CONNECTED', {\n reason: 'not_connected',\n operation: 'connect',\n });\n }\n const raw = Array.isArray(accounts) ? (accounts[0] as unknown) : undefined;\n if (raw === undefined) {\n throw new GalaSDKError('WALLET_CONNECTION_FAILED', { reason: 'no_accounts' });\n }\n const account = typeof raw === 'string' ? this.accountOf(raw) : undefined;\n if (account === undefined) {\n throw new GalaSDKError(\n 'WALLET_CONNECTION_FAILED',\n { reason: 'failed' },\n { cause: new TypeError('the wallet reported an account that is not an Ethereum address') },\n );\n }\n this.adopt(account);\n return account.address;\n }\n\n /**\n * Reconnects to the account the wallet already lets this site use, WITHOUT a wallet prompt (for\n * the page reload after an earlier `connect()`): asks `eth_accounts` only, never\n * `eth_requestAccounts`. When the wallet reports an account the provider is connected to it and\n * listens to the wallet's events, exactly as after `connect()`; otherwise it stays not connected\n * and holds no listener.\n *\n * Nothing here throws. The wallet reporting no account, an account that is not an Ethereum\n * address, or `eth_accounts` failing all answer `null`: a silent restore that cannot happen is\n * not an error, the user connects with `connect()`. A `disconnect()`, a wallet event or a\n * `connect()` that lands while the wallet is answering wins over the answer (it may be older than\n * they are); the provider then answers its state at that moment.\n *\n * @returns The connected account (`0x`, checksummed), or `null` when not connected. Already\n * connected: the connected account, with no request.\n */\n public async restore(): Promise<string | null> {\n if (this.account !== null) return this.account.address;\n // Any disconnect, release, wallet event or connect moves `version`; see the class invariants.\n const version = this.version;\n let accounts: unknown;\n try {\n accounts = await this.wallet.request<unknown>({ method: 'eth_accounts' });\n } catch {\n return null;\n }\n if (version !== this.version) {\n return this.currentAddress();\n }\n const raw = Array.isArray(accounts) ? (accounts[0] as unknown) : undefined;\n const account = typeof raw === 'string' ? this.accountOf(raw) : undefined;\n if (account === undefined) return null;\n this.adopt(account);\n return account.address;\n }\n\n /** True while the provider has an account to sign for. */\n public isConnected(): boolean {\n return this.account !== null;\n }\n\n /**\n * The connected account (`0x`, checksummed).\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`.\n */\n public async getAddress(): Promise<string> {\n return this.requireAccount('getAddress').address;\n }\n\n /**\n * The connected account as GalaChain spells it (`eth|` plus the checksummed digits).\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`.\n */\n public async getGalaAddress(): Promise<string> {\n return `eth|${this.requireAccount('getGalaAddress').address.slice(2)}`;\n }\n\n /**\n * A wallet-backed provider never holds the key.\n *\n * @throws GalaSDKError `PRIVATE_KEY_NOT_ACCESSIBLE`, always.\n */\n public async getPrivateKey(): Promise<string> {\n throw new GalaSDKError('PRIVATE_KEY_NOT_ACCESSIBLE', {});\n }\n\n /**\n * Calls `listener` with the new account whenever it changes (`null` once disconnected).\n *\n * @returns The function that stops the calls.\n */\n public onAccountChanged(listener: AccountListener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** The wallet object the provider talks to. */\n public getProvider(): W {\n return this.wallet;\n }\n\n /**\n * Retires this provider object WITHOUT asking the wallet to end its session (unlike\n * `disconnect()`, which revokes / disconnects in the wallet): it forgets the account and removes\n * its listeners from the wallet. For code that drops a provider it created, so the wallet keeps\n * no listener of a provider nobody uses (the React context does it when it switches wallets).\n */\n public release(): void {\n this.disconnectLocally();\n }\n\n /** The connected account, read once by an operation before its first await. */\n protected requireAccount(operation: string): WalletAccount {\n if (this.account === null) {\n throw new GalaSDKError('WALLET_NOT_CONNECTED', { reason: 'not_connected', operation });\n }\n return this.account;\n }\n\n /** The core error a wallet failure becomes; a disconnection also forgets the account. */\n protected failure(error: unknown, operation: WalletOperation): SdkError {\n const code = this.walletCodeOf(error);\n if (isWalletDisconnection(code)) this.forget();\n return walletFailure(error, code, operation);\n }\n\n /** Forgets the account (an explicit disconnect also voids a `connect()` still in flight). */\n protected disconnectLocally(): void {\n this.generation += 1;\n this.forget();\n }\n\n /** The account of an `0x` / bare-hex spelling, checksummed; `undefined` for anything else. */\n protected static ethereumAccount(raw: string, spelled: string): WalletAccount | undefined {\n const address = checksumEthereumAddress(spelled);\n return address === undefined ? undefined : { address, raw };\n }\n\n /** The connected account's address now (a read after an await: not narrowed by an earlier check). */\n private currentAddress(): string | null {\n return this.account?.address ?? null;\n }\n\n /** Connects to `account`: remembers it, listens to the wallet, tells the listeners. */\n private adopt(account: WalletAccount): void {\n this.account = account;\n this.version += 1;\n this.listen();\n this.notify(account.address);\n }\n\n private forget(): void {\n this.unlisten();\n this.version += 1;\n if (this.account === null) return;\n this.account = null;\n this.notify(null);\n }\n\n private listen(): void {\n if (this.listening || typeof this.wallet.on !== 'function') return;\n this.wallet.on('accountsChanged', this.onAccountsChanged);\n this.wallet.on('disconnect', this.onWalletDisconnect);\n this.listening = true;\n }\n\n private unlisten(): void {\n if (!this.listening) return;\n this.listening = false;\n if (typeof this.wallet.removeListener !== 'function') return;\n this.wallet.removeListener('accountsChanged', this.onAccountsChanged);\n this.wallet.removeListener('disconnect', this.onWalletDisconnect);\n }\n\n private notify(address: string | null): void {\n notifyAccountListeners(this.listeners, address);\n }\n}\n","/**\n * An EIP-1193 browser wallet (MetaMask, Coinbase Wallet, Trust Wallet, ...) as a\n * {@link WalletProvider}. The key never leaves the wallet: every signature is the wallet's.\n */\nimport { BrowserWalletSigner, walletDeclineCode, type GalaChainSigner } from '../index.js';\nimport type {\n Eip1193Provider,\n TypedDataDomain,\n TypedDataField,\n WalletProvider,\n WalletProviderType,\n} from './types.js';\nimport { WalletConnection, type WalletAccount } from './wallet_connection.js';\nimport { requestPersonalSignature, requestTypedDataSignature } from './wallet_requests.js';\n\n/**\n * A browser wallet behind EIP-1193.\n *\n * @example\n * ```typescript\n * const provider = new ExternalWalletProvider(window.ethereum);\n * const address = await provider.connect();\n * const signature = await provider.signMessage('Hello');\n * await provider.disconnect();\n * ```\n */\nexport class ExternalWalletProvider\n extends WalletConnection<Eip1193Provider>\n implements WalletProvider\n{\n public readonly providerType: WalletProviderType = 'external';\n\n /**\n * @param provider - The wallet's EIP-1193 provider (`window.ethereum`, an EIP-6963 announcement).\n * @throws GalaSDKError `INVALID_WALLET_PROVIDER_CONFIG` when no provider is given.\n */\n public constructor(provider: Eip1193Provider) {\n super(provider);\n }\n\n protected accountOf(raw: string): WalletAccount | undefined {\n return WalletConnection.ethereumAccount(raw, raw);\n }\n\n protected walletCodeOf(error: unknown): number | string | undefined {\n return walletDeclineCode(error);\n }\n\n /**\n * Revokes the account permission where the wallet supports it (`wallet_revokePermissions`) and\n * forgets the account.\n */\n public async disconnect(): Promise<void> {\n this.disconnectLocally();\n try {\n await this.wallet.request({\n method: 'wallet_revokePermissions',\n params: [{ eth_accounts: {} }],\n });\n } catch {\n // Not every wallet implements wallet_revokePermissions; the provider is disconnected anyway.\n }\n }\n\n /**\n * Signs `message` with `personal_sign` (the wallet applies EIP-191).\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`, `SIGNING_FAILED`, `INVALID_SIGNATURE`.\n */\n public async signMessage(message: string): Promise<string> {\n const { address } = this.requireAccount('personal_sign');\n try {\n return await requestPersonalSignature(this.wallet, address, message);\n } catch (error: unknown) {\n throw this.failure(error, 'personal_sign');\n }\n }\n\n /**\n * Signs EIP-712 typed data with `eth_signTypedData_v4`.\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`, `SIGNING_FAILED`, `INVALID_SIGNATURE`.\n */\n public async signTypedData(\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n value: Record<string, unknown>,\n ): Promise<string> {\n const { address } = this.requireAccount('eth_signTypedData_v4');\n try {\n return await requestTypedDataSignature(this.wallet, address, domain, types, value);\n } catch (error: unknown) {\n throw this.failure(error, 'eth_signTypedData_v4');\n }\n }\n\n /**\n * The core {@link BrowserWalletSigner} for GalaChain DTOs, bound to the account connected now.\n *\n * @param options - `{ scheme: 'eip712' }` signs the EIP-712-capable DEX methods with\n * `eth_signTypedData_v4` (resolving a registered `client|` alias); the default is `personal_sign`.\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`.\n */\n public getSigner(options: { scheme?: 'personal-sign' | 'eip712' } = {}): GalaChainSigner {\n const { address } = this.requireAccount('getSigner');\n return new BrowserWalletSigner(this.wallet, address, options);\n }\n}\n","/**\n * Gala Wallet (the `window.gala` extension, or the same object from an EIP-6963 announcement) as a\n * {@link WalletProvider}. Gala Wallet holds one current account and is switched to the account a\n * signature is for with `setAddress` before every signature; its errors are JSON strings.\n */\nimport {\n GalaWalletSigner,\n walletDeclineCode,\n withGalaWalletIdentity,\n type GalaChainSigner,\n type GalaWalletScheme,\n} from '../index.js';\nimport type {\n Eip1193Provider,\n TypedDataDomain,\n TypedDataField,\n WalletProvider,\n WalletProviderType,\n} from './types.js';\nimport { WalletConnection, type WalletAccount } from './wallet_connection.js';\nimport { requestPersonalSignature, requestTypedDataSignature } from './wallet_requests.js';\n\n/** The Gala Wallet extension's API: EIP-1193 plus its account switch and disconnect. */\nexport interface GalaWalletExtension extends Eip1193Provider {\n /** Makes `address` the account the next request signs as. */\n setAddress?(address: string): Promise<void>;\n /** Ends the wallet's session with this app. */\n disconnect?(): Promise<void>;\n}\n\n/** An identity `GalaWalletSigner` accepts for `selectAddress` (`eth|`, `0x`, `client|`, 24 hex). */\nconst SELECTABLE_IDENTITY =\n /^(?:eth\\|[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\\|)?[0-9a-fA-F]{24})$/u;\n\n/**\n * The wallet's code on an error: Gala Wallet throws `Error`s whose message is a JSON object with a\n * numeric `code`; anything else is read as any wallet error is.\n */\nfunction galaWalletCode(error: unknown): number | string | undefined {\n if (error instanceof Error) {\n try {\n const parsed: unknown = JSON.parse(error.message);\n const code: unknown =\n typeof parsed === 'object' && parsed !== null\n ? (parsed as { code?: unknown }).code\n : undefined;\n if (typeof code === 'number') return code;\n } catch {\n // Not JSON: fall through to the error's own code.\n }\n }\n return walletDeclineCode(error);\n}\n\n/**\n * Gala Wallet as a wallet provider.\n *\n * @example\n * ```typescript\n * const provider = new GalaWalletProvider(window.gala);\n * const address = await provider.connect();\n * const signature = await provider.signMessage('Hello');\n * ```\n */\nexport class GalaWalletProvider\n extends WalletConnection<GalaWalletExtension>\n implements WalletProvider\n{\n public readonly providerType: WalletProviderType = 'external';\n\n /**\n * @param provider - Gala Wallet (`window.gala`, or its EIP-6963 announcement's provider).\n * @throws GalaSDKError `INVALID_WALLET_PROVIDER_CONFIG` when no provider is given.\n */\n public constructor(provider: GalaWalletExtension) {\n super(provider);\n }\n\n /**\n * Gala Wallet reports `eth|<40 hex>`, `0x<40 hex>` or the bare digits: all one account. An\n * `eth|0x...` is not an address form and is no account (`undefined`).\n */\n protected accountOf(raw: string): WalletAccount | undefined {\n if (/^eth\\|0[xX]/u.test(raw)) return undefined;\n return WalletConnection.ethereumAccount(raw, raw.startsWith('eth|') ? raw.slice(4) : raw);\n }\n\n protected walletCodeOf(error: unknown): number | string | undefined {\n return galaWalletCode(error);\n }\n\n /** Forgets the account and ends the wallet's session (`disconnect`, where it offers one). */\n public async disconnect(): Promise<void> {\n this.disconnectLocally();\n try {\n await this.wallet.disconnect?.();\n } catch {\n // The wallet's own disconnect failing leaves this provider disconnected anyway.\n }\n }\n\n /**\n * Signs `message` with `personal_sign`, after switching Gala Wallet to the connected account.\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`, `SIGNING_FAILED`, `INVALID_SIGNATURE`.\n */\n public async signMessage(message: string): Promise<string> {\n const { address, raw } = this.requireAccount('personal_sign');\n try {\n return await withGalaWalletIdentity(this.wallet, raw, () =>\n requestPersonalSignature(this.wallet, address, message),\n );\n } catch (error: unknown) {\n throw this.failure(error, 'personal_sign');\n }\n }\n\n /**\n * Signs EIP-712 typed data with `eth_signTypedData_v4`, after switching Gala Wallet to the\n * connected account.\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`, `SIGNING_FAILED`, `INVALID_SIGNATURE`.\n */\n public async signTypedData(\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n value: Record<string, unknown>,\n ): Promise<string> {\n const { address, raw } = this.requireAccount('eth_signTypedData_v4');\n try {\n return await withGalaWalletIdentity(this.wallet, raw, () =>\n requestTypedDataSignature(this.wallet, address, domain, types, value),\n );\n } catch (error: unknown) {\n throw this.failure(error, 'eth_signTypedData_v4');\n }\n }\n\n /**\n * The core {@link GalaWalletSigner} for GalaChain DTOs, bound to the account connected now and\n * signing through this provider's wallet object.\n *\n * @param options - `{ scheme: 'personal-sign' }` opts into Gala Wallet's personal-sign scheme\n * (see `GalaWalletSigner`); the default is native signing.\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`.\n */\n public getSigner(options: { scheme?: GalaWalletScheme } = {}): GalaChainSigner {\n const { address, raw } = this.requireAccount('getSigner');\n return new GalaWalletSigner(address, {\n scheme: options.scheme,\n selectAddress: SELECTABLE_IDENTITY.test(raw) ? raw : address,\n wallet: this.wallet,\n });\n }\n}\n","/**\n * A private key as a {@link WalletProvider}: signatures computed locally with core's secp256k1\n * primitives (no ethers), byte-identical to the ethers `Wallet` this provider wrapped before it\n * moved here (pinned by launchpad-sdk's `wallet-providers.golden.json`).\n */\nimport { bytesToHex } from '@noble/hashes/utils';\nimport {\n calculatePersonalSignPrefix,\n checksumEthereumAddress,\n ethAddressOfPrivateKey,\n GalaSDKError,\n isGalaError,\n normalizePrivateKey,\n PrivateKeySigner,\n signPersonalMessage,\n signTypedDataPayload,\n type GalaChainSigner,\n} from '../index.js';\nimport type {\n TypedDataDomain,\n TypedDataField,\n WalletProvider,\n WalletProviderType,\n} from './types.js';\nimport { notifyAccountListeners, type AccountListener } from './wallet_connection.js';\nimport type { SdkError } from './wallet_requests.js';\n\n/** The key spellings accepted: `0x` plus 64 hex digits, or the 64 digits (as ethers' `Wallet`). */\nconst KEY_SPELLING = /^(?:0x)?[0-9a-fA-F]{64}$/u;\n\n/** True when `message` has a lone UTF-16 surrogate: it has no UTF-8 encoding to sign. */\nfunction hasUnpairedSurrogate(message: string): boolean {\n for (let index = 0; index < message.length; index += 1) {\n const unit = message.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = message.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return true;\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * The domain fields that are set: ethers hashed only the fields that are not `null` /\n * `undefined`, and this provider signs exactly what it did.\n */\nfunction presentDomain(domain: TypedDataDomain): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(domain).filter(([, value]) => value !== undefined && value !== null),\n );\n}\n\n/** The core error a local signing failure becomes: an SDK error as it is, anything else `failed`. */\nfunction signingFailure(error: unknown, method: string): SdkError {\n return isGalaError(error)\n ? error\n : new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause: error });\n}\n\n/**\n * A wallet provider over a private key. Always ready to sign: `connect()` / `disconnect()` only\n * toggle `isConnected()`.\n *\n * @example\n * ```typescript\n * const provider = new PrivateKeyProvider(process.env.PRIVATE_KEY!);\n * const signature = await provider.signMessage('Hello');\n * const signer = provider.getSigner(); // native GalaChain signing\n * ```\n */\nexport class PrivateKeyProvider implements WalletProvider {\n public readonly providerType: WalletProviderType = 'privateKey';\n\n /** The key, `0x` plus 64 lower-case hex digits. Private: never enumerated or serialized. */\n readonly #privateKey: string;\n readonly #address: string;\n #connected = true;\n readonly #listeners = new Set<AccountListener>();\n\n /**\n * @param privateKey - `0x` plus 64 hex digits, or the 64 digits (any case).\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` (`bad_encoding`, `not_on_curve`). The key is never\n * part of the error.\n */\n public constructor(privateKey: string) {\n if (typeof privateKey !== 'string' || !KEY_SPELLING.test(privateKey)) {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n const key = normalizePrivateKey(privateKey);\n try {\n this.#privateKey = `0x${bytesToHex(key)}`;\n // A derived address is always `0x` plus 40 lower-case hex digits, which always checksums.\n this.#address = checksumEthereumAddress(ethAddressOfPrivateKey(key)) as string;\n } finally {\n key.fill(0);\n }\n }\n\n /** A provider over the key an ethers `Wallet` (or any `{ privateKey }`) holds. */\n public static fromWallet(wallet: { readonly privateKey: string }): PrivateKeyProvider {\n return new PrivateKeyProvider(wallet.privateKey);\n }\n\n /**\n * Signs `message` as `personal_sign` does (EIP-191 over its UTF-8 bytes).\n *\n * @throws GalaSDKError `SIGNING_FAILED` for a message with a lone surrogate (it has no UTF-8\n * encoding; a wallet would sign U+FFFD instead of what was shown).\n */\n public async signMessage(message: string): Promise<string> {\n try {\n if (hasUnpairedSurrogate(message)) {\n throw new TypeError('the message has a lone UTF-16 surrogate, which has no UTF-8 encoding');\n }\n const key = normalizePrivateKey(this.#privateKey);\n try {\n return `0x${signPersonalMessage(key, calculatePersonalSignPrefix(message), message)}`;\n } finally {\n key.fill(0);\n }\n } catch (error: unknown) {\n throw signingFailure(error, 'personal_sign');\n }\n }\n\n /**\n * Signs EIP-712 typed data (`eth_signTypedData_v4`) with core's encoder, which fails closed on a\n * value ethers would have coerced (`TYPED_DATA_*`).\n *\n * @throws GalaSDKError `TYPED_DATA_*` for typed data the encoder refuses, `SIGNING_FAILED`.\n */\n public async signTypedData(\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n value: Record<string, unknown>,\n ): Promise<string> {\n try {\n return await signTypedDataPayload(this.#privateKey, {\n domain: presentDomain(domain),\n types,\n message: value,\n });\n } catch (error: unknown) {\n throw signingFailure(error, 'eth_signTypedData_v4');\n }\n }\n\n /** The key's account: `0x` plus the EIP-55 digits. */\n public async getAddress(): Promise<string> {\n return this.#address;\n }\n\n /** The key's account as GalaChain spells it: `eth|` plus the EIP-55 digits. */\n public async getGalaAddress(): Promise<string> {\n return `eth|${this.#address.slice(2)}`;\n }\n\n /** The core {@link PrivateKeySigner} (native GalaChain signing) over this key. */\n public getSigner(): GalaChainSigner {\n return new PrivateKeySigner(this.#privateKey);\n }\n\n /** Marks the provider connected (it always can sign) and returns its account. */\n public async connect(): Promise<string> {\n this.#connected = true;\n this.#notify(this.#address);\n return this.#address;\n }\n\n /** Marks the provider disconnected; it can still sign. */\n public async disconnect(): Promise<void> {\n this.#connected = false;\n this.#notify(null);\n }\n\n /** True until `disconnect()` (again after `connect()`). */\n public isConnected(): boolean {\n return this.#connected;\n }\n\n /** The key: `0x` plus 64 lower-case hex digits. */\n public async getPrivateKey(): Promise<string> {\n return this.#privateKey;\n }\n\n /**\n * The key, synchronously: `0x` plus 64 lower-case hex digits. For code that must build its own\n * signer from it (an ethers `Wallet`) in a synchronous path.\n */\n public exportPrivateKey(): string {\n return this.#privateKey;\n }\n\n /**\n * Calls `listener` with the account on `connect()` and `null` on `disconnect()`.\n *\n * @returns The function that stops the calls.\n */\n public onAccountChanged(listener: AccountListener): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #notify(address: string | null): void {\n notifyAccountListeners(this.#listeners, address);\n }\n}\n","/**\n * Browser wallet detection: EIP-6963 announcements, with the injected globals as a fallback\n * (`window.ethereum`, Trust Wallet behind another wallet, `window.gala`).\n *\n * Safe everywhere: without a browser window (Node, SSR, React Native, an MV3 service worker) every\n * function returns \"nothing found\" and nothing throws. Announcements are read structurally and a\n * malformed one is ignored, never trusted.\n */\nimport type {\n DetectedWallet,\n Eip1193Provider,\n Eip6963ProviderInfo,\n WalletDetectionResult,\n} from './types.js';\n\n/** The reverse-DNS ids of well-known wallets. */\nexport const KNOWN_WALLET_RDNS = {\n METAMASK: 'io.metamask',\n METAMASK_FLASK: 'io.metamask.flask',\n COINBASE: 'com.coinbase.wallet',\n TRUST_WALLET: 'com.trustwallet.app',\n PHANTOM: 'app.phantom',\n RAINBOW: 'me.rainbow',\n OKX: 'com.okex.wallet',\n RABBY: 'io.rabby',\n BRAVE: 'com.brave.wallet',\n FRAME: 'sh.frame',\n LEDGER: 'com.ledger',\n ZERION: 'io.zerion.wallet',\n GALA: 'com.gala.wallet',\n} as const;\n\n/** Default icons (data URIs) of known wallets, used when a wallet announces none. */\nconst DEFAULT_WALLET_ICONS: Readonly<Record<string, string>> = {\n [KNOWN_WALLET_RDNS.METAMASK]:\n 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIxLjU0IDQuMjJsLTguMzQgNi4yMSAxLjU0LTMuNjUtLTUuNTMtMi41MXoiIGZpbGw9IiNFMjc2MUIiLz48L3N2Zz4=',\n [KNOWN_WALLET_RDNS.GALA]:\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAYAAACoYAD2AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAjWSURBVHgBzZkLVI1ZG8f/pZKjq0uK0LglIiMKU5EuBkMxUgmjL6GFSZJ7QpJx+Ujpk1Eat3KJySXjTnIpVJRPhnTSxWVaSveL1Zlnv3WshnM67wlrzX+t3T5nv3vv99d+9/O8z36OAj5DIpGoM1W2VPSp6FJp03ipmkoRlVwq9xUUFDLwGVKCnCKwAVRNqa2rc8vOLeiRkpqpcO/hY7woeI3yikrUva9DG1VV6HXqiJHDv0Uvg66oqa0VqigrX6dxUQScCDmlwLcjwfWjKuhJdq5jVMwpxMRfQP7LN7zGttPWxARbC3i4OsDCzOQuNQUS7Gnwl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3KBJigJeTUtDXaiq274nhBei/yIMBHm4K+A/IRoW6TLQ7tWTedPARy6ot3RAKE9tpeNj4btZQb8tZ92SPpbBzWcj73M0C4DU+s4X08RNrkpTBYA7xhrf/tj6h+45CHhn27M7lKCsoyGhu332sQcZ9kBgXUazWVmBKq5gDWZCNoAaUTUugk54RiwG/puzo9Bm5zb+MTqRsH96U1Ke5rBrzL/E7I48MXkFWXVVdgy+txXPdsHG5F8sC2xOg1BOdrPwke734ZQvzV09fuAbJaY/wJdRFVwcRvyzHOJvvLtPXaQTYbMqYVzqaYCdQ2UFZ3h6U7QVlfdESMec/d8Yk+M51e01gLCcZzmcc75x5I+wMquanZz4xjz52FiyhzwIJ5uglSYlSKz0IzMJ8ENwoUrccNjhLSVHxAF0KI8BS8JRckE1gzamyp/J94auiITl5BSpvS0rJsqu4Xx8E9OsDi9D19TrVUyovh+KFOOp7nsptgpM7Em4R5EfArdDwOw5L7rAsATvcFVMRskJQsr24DP0NVvGaoREi2pYAAAAASUVORK5CYII=',\n};\n\n/** The parts of a browser window detection uses (structural: no DOM types). */\ninterface BrowserWindow {\n addEventListener(type: string, listener: (event: unknown) => void): void;\n removeEventListener(type: string, listener: (event: unknown) => void): void;\n dispatchEvent(event: unknown): boolean;\n Event?: new (type: string) => unknown;\n ethereum?: unknown;\n gala?: unknown;\n trustwallet?: unknown;\n trustWallet?: unknown;\n}\n\nconst ANNOUNCE = 'eip6963:announceProvider';\nconst REQUEST = 'eip6963:requestProvider';\n/** The window event Trust Wallet fires once its provider is injected (it can be after page load). */\nconst TRUST_INITIALIZED = 'trustwallet#initialized';\n/** How long {@link getTrustWallet} waits for {@link TRUST_INITIALIZED} by default. */\nconst TRUST_INIT_WAIT_MS = 3000;\n\n/** The browser window, or `undefined` outside a browser (no `window`, or one that cannot dispatch). */\nfunction browserWindow(): BrowserWindow | undefined {\n const candidate: unknown = (globalThis as { window?: unknown }).window;\n if (typeof candidate !== 'object' || candidate === null) return undefined;\n const window = candidate as Partial<BrowserWindow>;\n return typeof window.dispatchEvent === 'function' &&\n typeof window.addEventListener === 'function' &&\n typeof window.removeEventListener === 'function'\n ? (candidate as BrowserWindow)\n : undefined;\n}\n\n/** An EIP-1193 provider with the identity flags injected wallets set on themselves. */\ntype TrustCandidate = Eip1193Provider & { isTrust?: boolean; isMetaMask?: boolean };\n\nfunction isRequestable(candidate: unknown): candidate is TrustCandidate {\n return (\n typeof candidate === 'object' &&\n candidate !== null &&\n typeof (candidate as { request?: unknown }).request === 'function'\n );\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n/** An EIP-6963 announcement read: the wallet it describes and the announcement's uuid. */\ninterface Announcement {\n readonly wallet: DetectedWallet;\n readonly uuid: string;\n}\n\n/** The wallet an EIP-6963 announcement describes, or `undefined` for a malformed one. */\nfunction announcement(event: unknown): Announcement | undefined {\n const detail: unknown =\n typeof event === 'object' && event !== null\n ? (event as { detail?: unknown }).detail\n : undefined;\n if (typeof detail !== 'object' || detail === null) return undefined;\n const { info, provider } = detail as { info?: unknown; provider?: unknown };\n if (typeof info !== 'object' || info === null || !isRequestable(provider)) return undefined;\n const { uuid, name, icon, rdns } = info as Partial<Record<keyof Eip6963ProviderInfo, unknown>>;\n if (!isString(uuid) || !isString(name)) return undefined;\n const id = isString(rdns) && rdns !== '' ? rdns : uuid;\n const wallet: DetectedWallet = {\n id,\n name,\n rdns: id,\n icon: isString(icon) ? icon : (DEFAULT_WALLET_ICONS[isString(rdns) ? rdns : ''] ?? ''),\n provider,\n isInjected: false,\n };\n return { wallet, uuid };\n}\n\n/**\n * Asks every EIP-6963 wallet to announce itself (when the environment can build the event). The\n * event is built with the WINDOW's own `Event` (in a browser the same as the global one): an event\n * from another realm (a test DOM, an iframe) is refused by `dispatchEvent`.\n */\nfunction requestAnnouncements(window: BrowserWindow): void {\n const EventConstructor =\n window.Event ?? (globalThis as { Event?: new (type: string) => unknown }).Event;\n if (typeof EventConstructor === 'function') window.dispatchEvent(new EventConstructor(REQUEST));\n}\n\n/** The injected `window.ethereum` when it is an EIP-1193 provider. */\nfunction injectedProvider(window: BrowserWindow | undefined): TrustCandidate | undefined {\n const ethereum = window?.ethereum;\n return isRequestable(ethereum) ? ethereum : undefined;\n}\n\n/**\n * Trust Wallet's injected provider, also when another wallet owns `window.ethereum`: it can sit in\n * the non-standard `window.ethereum.providers` array or only in its own `window.trustwallet`.\n */\nfunction trustWalletProvider(window: BrowserWindow): Eip1193Provider | undefined {\n const ethereum = injectedProvider(window);\n if (ethereum?.isTrust === true) return ethereum;\n const providers: unknown =\n typeof window.ethereum === 'object' && window.ethereum !== null\n ? (window.ethereum as { providers?: unknown }).providers\n : undefined;\n if (Array.isArray(providers)) {\n const found: unknown = providers.find(\n (candidate: unknown) => isRequestable(candidate) && candidate.isTrust === true,\n );\n if (isRequestable(found)) return found;\n }\n if (isRequestable(window.trustwallet)) return window.trustwallet;\n // The camel-cased global is read as a fallback, and only when it says it is Trust Wallet.\n const camel: unknown = window.trustWallet;\n return isRequestable(camel) && camel.isTrust === true ? camel : undefined;\n}\n\n/** True for a provider that is MetaMask itself: it says so, and is not Trust Wallet posing as it. */\nfunction isMetaMaskProvider(provider: unknown): boolean {\n return isRequestable(provider) && provider.isMetaMask === true && provider.isTrust !== true;\n}\n\n/** True for a provider that says it is Trust Wallet. */\nfunction isTrustProvider(provider: unknown): boolean {\n return isRequestable(provider) && provider.isTrust === true;\n}\n\n/**\n * MetaMask's injected provider: `window.ethereum` when it is MetaMask, else the MetaMask entry of\n * the non-standard `window.ethereum.providers` array a multi-wallet browser keeps. Never Trust\n * Wallet, which sets `isMetaMask` on itself too.\n */\nfunction injectedMetaMask(window: BrowserWindow): Eip1193Provider | undefined {\n const ethereum = injectedProvider(window);\n if (ethereum === undefined) return undefined;\n if (isMetaMaskProvider(ethereum)) return ethereum;\n const providers: unknown = (ethereum as { providers?: unknown }).providers;\n if (!Array.isArray(providers)) return undefined;\n const found: unknown = providers.find(isMetaMaskProvider);\n return isRequestable(found) ? found : undefined;\n}\n\nfunction injectedWallet(id: string, name: string, provider: Eip1193Provider): DetectedWallet {\n return { id, name, rdns: id, icon: DEFAULT_WALLET_ICONS[id] ?? '', provider, isInjected: true };\n}\n\n/** The injected wallets, as the fallback after the announcement window closed. */\nfunction injectedFallback(window: BrowserWindow, found: DetectedWallet[]): DetectedWallet[] {\n const wallets = [...found];\n const has = (id: string): boolean => wallets.some((wallet) => wallet.id === id);\n const ethereum = injectedProvider(window);\n if (wallets.length === 0 && ethereum !== undefined) {\n const flags = ethereum as { isCoinbaseWallet?: boolean };\n if (isMetaMaskProvider(ethereum)) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.METAMASK, 'MetaMask', ethereum));\n } else if (flags.isCoinbaseWallet === true) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.COINBASE, 'Coinbase Wallet', ethereum));\n } else if (ethereum.isTrust === true) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.TRUST_WALLET, 'Trust Wallet', ethereum));\n } else {\n wallets.push(injectedWallet('injected', 'Browser Wallet', ethereum));\n }\n }\n // MetaMask behind another wallet (the multi-injection `providers` array), unless a MetaMask is\n // already listed: by its rdns, or as an announcement that says `isMetaMask` (Rabby and Brave do).\n const metamask = injectedMetaMask(window);\n if (\n metamask !== undefined &&\n !wallets.some(\n (wallet) =>\n wallet.id === KNOWN_WALLET_RDNS.METAMASK ||\n wallet.id === KNOWN_WALLET_RDNS.METAMASK_FLASK ||\n isMetaMaskProvider(wallet.provider),\n )\n ) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.METAMASK, 'MetaMask', metamask));\n }\n // Trust Wallet is listed once, also when it announced under another rdns but says `isTrust`.\n if (\n !has(KNOWN_WALLET_RDNS.TRUST_WALLET) &&\n !wallets.some((wallet) => isTrustProvider(wallet.provider))\n ) {\n const trust = trustWalletProvider(window);\n if (trust !== undefined && !wallets.some((wallet) => wallet.provider === trust)) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.TRUST_WALLET, 'Trust Wallet', trust));\n }\n }\n if (isRequestable(window.gala) && !has(KNOWN_WALLET_RDNS.GALA)) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.GALA, 'Gala Wallet', window.gala));\n }\n return wallets;\n}\n\nfunction resultOf(wallets: DetectedWallet[]): WalletDetectionResult {\n return {\n wallets,\n byId: new Map(wallets.map((wallet) => [wallet.id, wallet])),\n hasWallets: wallets.length > 0,\n ...(wallets[0] === undefined ? {} : { primary: wallets[0] }),\n };\n}\n\n/**\n * The wallets in this browser: every EIP-6963 announcement within `timeout` ms (one per uuid),\n * then the injected fallbacks (`window.ethereum` when nothing announced, Trust Wallet, Gala Wallet).\n * Outside a browser it resolves to \"nothing found\" at once.\n *\n * @example\n * ```typescript\n * const { wallets, primary } = await detectWallets();\n * if (primary) await new ExternalWalletProvider(primary.provider).connect();\n * ```\n */\nexport async function detectWallets(timeout: number = 500): Promise<WalletDetectionResult> {\n const window = browserWindow();\n if (window === undefined) return resultOf([]);\n\n return new Promise((resolve) => {\n const wallets: DetectedWallet[] = [];\n const seen = new Set<string>();\n const onAnnounce = (event: unknown): void => {\n const announced = announcement(event);\n // Some wallets announce more than once: one entry per announcement uuid.\n if (announced === undefined || seen.has(announced.uuid)) return;\n seen.add(announced.uuid);\n wallets.push(announced.wallet);\n };\n window.addEventListener(ANNOUNCE, onAnnounce);\n requestAnnouncements(window);\n setTimeout(() => {\n window.removeEventListener(ANNOUNCE, onAnnounce);\n resolve(resultOf(injectedFallback(window, wallets)));\n }, timeout);\n });\n}\n\n/**\n * Calls `callback` with the detected wallets now and again whenever a new wallet announces itself.\n * Outside a browser it never calls and the returned function does nothing.\n *\n * @returns The function that stops the calls and the listening.\n */\nexport function subscribeToWalletChanges(\n callback: (result: WalletDetectionResult) => void,\n): () => void {\n const window = browserWindow();\n if (window === undefined) return () => undefined;\n\n let subscribed = true;\n let current: DetectedWallet[] = [];\n const onAnnounce = (event: unknown): void => {\n const wallet = announcement(event)?.wallet;\n if (!subscribed || wallet === undefined || current.some((known) => known.id === wallet.id)) {\n return;\n }\n current = [...current, wallet];\n callback(resultOf(current));\n };\n window.addEventListener(ANNOUNCE, onAnnounce);\n void detectWallets().then((result) => {\n if (!subscribed) return;\n current = result.wallets;\n callback(result);\n });\n return () => {\n subscribed = false;\n window.removeEventListener(ANNOUNCE, onAnnounce);\n };\n}\n\n/** The detected wallet with reverse-DNS id `rdns`, or `null`. */\nexport async function getWalletByRdns(\n rdns: string,\n timeout?: number,\n): Promise<DetectedWallet | null> {\n const result = await detectWallets(timeout);\n return result.byId.get(rdns) ?? null;\n}\n\n/** True when the wallet with reverse-DNS id `rdns` is detected. */\nexport async function isWalletAvailable(rdns: string, timeout?: number): Promise<boolean> {\n return (await getWalletByRdns(rdns, timeout)) !== null;\n}\n\n/**\n * MetaMask among detected wallets, in this order: an announcement with rdns `io.metamask` or\n * `io.metamask.flask`; else any listed provider that says `isMetaMask` and is not `isTrust` (an\n * announcement, `window.ethereum`, or its `providers[]` entry; Trust Wallet sets `isMetaMask` on\n * itself, and is never returned here); else `undefined`.\n *\n * It is a lookup, not a relabelling: `detectWallets` still lists a wallet that announces itself as\n * Rabby or Brave (which also say `isMetaMask`) under its own rdns.\n */\nexport function findMetaMaskWallet(result: WalletDetectionResult): DetectedWallet | undefined {\n return (\n result.wallets.find(\n (wallet) =>\n wallet.id === KNOWN_WALLET_RDNS.METAMASK || wallet.id === KNOWN_WALLET_RDNS.METAMASK_FLASK,\n ) ?? result.wallets.find((wallet) => isMetaMaskProvider(wallet.provider))\n );\n}\n\n/**\n * Trust Wallet among detected wallets: the listed wallet with rdns `com.trustwallet.app`, else any\n * listed provider that says `isTrust` (an announcement under another rdns, `window.ethereum`, its\n * `providers[]` entry), else `undefined`.\n */\nexport function findTrustWallet(result: WalletDetectionResult): DetectedWallet | undefined {\n return result.wallets.find(\n (wallet) => wallet.id === KNOWN_WALLET_RDNS.TRUST_WALLET || isTrustProvider(wallet.provider),\n );\n}\n\n/** MetaMask in this browser (see {@link findMetaMaskWallet}), or `null`. */\nexport async function getMetaMaskWallet(timeout?: number): Promise<DetectedWallet | null> {\n return findMetaMaskWallet(await detectWallets(timeout)) ?? null;\n}\n\n/** Resolves when `window` fires {@link TRUST_INITIALIZED} or after `timeout` ms, whichever is first. */\nfunction trustInitialized(window: BrowserWindow, timeout: number): Promise<void> {\n return new Promise((resolve) => {\n const done = (): void => {\n clearTimeout(timer);\n window.removeEventListener(TRUST_INITIALIZED, done);\n resolve();\n };\n // `done` runs only after both lines below (an event or the timer), never inside them.\n window.addEventListener(TRUST_INITIALIZED, done);\n const timer = setTimeout(done, timeout);\n });\n}\n\n/**\n * Trust Wallet in this browser (see {@link findTrustWallet}; also `window.trustwallet` /\n * `window.trustWallet`). Trust Wallet can inject after the page loaded, so when it is not found at\n * once this waits up to `options.timeout` ms (default 3000) for its `trustwallet#initialized`\n * window event and looks again; it never waits when the wallet is already there. Resolves `null`\n * when it is not found, and at once without a browser window.\n *\n * @param options - `timeout`: the most to wait for the initialized event; `announceTimeout`: the\n * EIP-6963 announcement window of the first look (see {@link detectWallets}).\n */\nexport async function getTrustWallet(\n options: { timeout?: number; announceTimeout?: number } = {},\n): Promise<DetectedWallet | null> {\n const found = findTrustWallet(await detectWallets(options.announceTimeout));\n if (found !== undefined) return found;\n const window = browserWindow();\n if (window === undefined) return null;\n await trustInitialized(window, options.timeout ?? TRUST_INIT_WAIT_MS);\n return findTrustWallet(await detectWallets(0)) ?? null;\n}\n\n/** True at once (no waiting) when an injected `window.ethereum` provider exists. */\nexport function hasAnyWallet(): boolean {\n return injectedProvider(browserWindow()) !== undefined;\n}\n\n/** The injected `window.ethereum` provider, or `null` (also outside a browser). */\nexport function getInjectedEip1193Provider(): Eip1193Provider | null {\n return injectedProvider(browserWindow()) ?? null;\n}\n","/**\n * Building and inspecting wallet providers.\n */\nimport { GalaSDKError } from '../index.js';\nimport { ExternalWalletProvider } from './external_wallet_provider.js';\nimport { PrivateKeyProvider } from './private_key_provider.js';\nimport type { Eip1193Provider, WalletProvider, WalletProviderConfig } from './types.js';\n\n/**\n * The provider a config describes: a {@link PrivateKeyProvider} for a non-empty `privateKey`\n * (preferred when both are given), else an {@link ExternalWalletProvider} for `eip1193Provider`.\n *\n * @throws GalaSDKError `INVALID_WALLET_PROVIDER_CONFIG` when the config has neither,\n * `INVALID_PRIVATE_KEY` for a key that is not one.\n *\n * @example\n * ```typescript\n * const provider = createWalletProvider({ eip1193Provider: window.ethereum });\n * await provider.connect();\n * ```\n */\nexport function createWalletProvider(config: WalletProviderConfig): WalletProvider {\n if (config.privateKey !== undefined && config.privateKey.length > 0) {\n return new PrivateKeyProvider(config.privateKey);\n }\n if (config.eip1193Provider !== undefined && config.eip1193Provider !== null) {\n return new ExternalWalletProvider(config.eip1193Provider);\n }\n throw new GalaSDKError('INVALID_WALLET_PROVIDER_CONFIG', {\n missing: 'private_key_or_eip1193_provider',\n });\n}\n\n/** An {@link ExternalWalletProvider} over an EIP-1193 provider. */\nexport function createProviderFromEip1193(provider: Eip1193Provider): ExternalWalletProvider {\n return new ExternalWalletProvider(provider);\n}\n\n/** True for a provider that holds a raw key (a {@link PrivateKeyProvider}). */\nexport function isPrivateKeyProvider(provider: WalletProvider): provider is PrivateKeyProvider {\n return provider.providerType === 'privateKey' && provider instanceof PrivateKeyProvider;\n}\n\n/** True for a provider that signs in a wallet. */\nexport function isExternalProvider(provider: WalletProvider): boolean {\n return provider.providerType === 'external';\n}\n\n/** The provider's raw key when it has one, else `undefined` (never throws). */\nexport async function getPrivateKeyIfAvailable(\n provider: WalletProvider,\n): Promise<string | undefined> {\n if (!isPrivateKeyProvider(provider)) return undefined;\n return provider.getPrivateKey();\n}\n\n/** The connected account, connecting first when the provider is not connected. */\nexport async function ensureConnected(provider: WalletProvider): Promise<string> {\n return provider.isConnected() ? provider.getAddress() : provider.connect();\n}\n\n/** True for an object with an EIP-1193 `request` method. */\nexport function isEip1193Provider(value: unknown): value is Eip1193Provider {\n return (\n typeof value === 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iB,UACnC,CAGA,eAAsBuG,GACpB,EAC6B,CAC7B,GAAKF,EAAqBrG,CAAQ,EAClC,OAAOA,EAAS,cAAc,CAChC,CAGA,eAAsBwG,GAAgB,EAA2C,CAC/E,OAAOxG,EAAS,YAAY,EAAIA,EAAS,WAAW,EAAIA,EAAS,QAAQ,CAC3E,CAGA,SAAgByG,GAAkB,EAA0C,CAC1E,OACE,OAAOhJ,GAAU,YACjBA,GACA,OAAQA,EAAgC,SAAY,UAExD,C"}
1
+ {"version":3,"file":"providers.js","names":["textEncoder","eip712DomainType","fields","domain","serializeTypedDataDomain","result","\"name\"","\"version\"","\"chainId\"","\"verifyingContract\"","\"salt\"","buildTypedDataPayload","types","encodePersonalSignMessage","bytesToHex","message","signatureOf","value","GalaSDKError","requestPersonalSignature","wallet","address","requestTypedDataSignature","DISCONNECTED","isWalletDisconnection","code","walletFailure","isGalaError","error","context","walletDeclineCode","reason","isWalletUserRejection","operation","_typeof","o","toPrimitive","t","e","i","r","toPropertyKey","_defineProperty","notifyAccountListeners","listener","listeners","WalletConnection","args","accounts","raw","account","generation","version","checksumEthereumAddress","spelled","ExternalWalletProvider","provider","BrowserWalletSigner","options","SELECTABLE_IDENTITY","galaWalletCode","parsed","GalaWalletProvider","withGalaWalletIdentity","GalaWalletSigner","_checkPrivateRedeclaration","_classPrivateMethodInitSpec","a","_classPrivateFieldInitSpec","_assertClassBrand","_classPrivateFieldSet2","s","_classPrivateFieldGet2","KEY_SPELLING","hasUnpairedSurrogate","index","unit","next","presentDomain","signingFailure","_privateKey","_address","_connected","_listeners","_PrivateKeyProvider_brand","PrivateKeyProvider","privateKey","key","normalizePrivateKey","ethAddressOfPrivateKey","signPersonalMessage","calculatePersonalSignPrefix","signTypedDataPayload","PrivateKeySigner","_notify","KNOWN_WALLET_RDNS","DEFAULT_WALLET_ICONS","ANNOUNCE","TRUST_INITIALIZED","browserWindow","candidate","window","isRequestable","isString","announcement","detail","event","info","uuid","name","id","rdns","icon","requestAnnouncements","EventConstructor","injectedProvider","ethereum","trustWalletProvider","providers","found","camel","isMetaMaskProvider","isTrustProvider","injectedMetaMask","injectedWallet","injectedFallback","wallets","has","flags","metamask","trust","resultOf","detectWallets","seen","onAnnounce","announced","resolve","timeout","subscribeToWalletChanges","subscribed","current","known","callback","getWalletByRdns","isWalletAvailable","findMetaMaskWallet","findTrustWallet","getMetaMaskWallet","trustInitialized","done","timer","getTrustWallet","hasAnyWallet","getInjectedEip1193Provider","createWalletProvider","config","createProviderFromEip1193","isPrivateKeyProvider","isExternalProvider","getPrivateKeyIfAvailable","ensureConnected","isEip1193Provider"],"sources":["../../src/providers/wallet_requests.ts","../../src/providers/wallet_connection.ts","../../src/providers/external_wallet_provider.ts","../../src/providers/gala_wallet_provider.ts","../../src/providers/private_key_provider.ts","../../src/providers/detection.ts","../../src/providers/provider_utils.ts"],"sourcesContent":["/**\n * The requests a wallet-backed provider sends (`personal_sign`, `eth_signTypedData_v4`) and the one\n * mapping of what a wallet throws onto the core error codes. The bytes handed to a wallet are pinned\n * by launchpad-sdk's `wallet-providers.golden.json` (captured before the move from launchpad-sdk).\n */\nimport { bytesToHex } from '@noble/hashes/utils';\nimport {\n GalaSDKError,\n isGalaError,\n isWalletUserRejection,\n walletDeclineCode,\n type GalaErrorParamsShape,\n} from '../index.js';\nimport type { TypedDataDomain, TypedDataField } from './types.js';\n\n/** Any SDK error: core's, or a product SDK's subclass passed through as it is. */\nexport type SdkError = GalaSDKError<string, GalaErrorParamsShape>;\n\n/** The request surface of an EIP-1193 wallet (and of Gala Wallet). */\nexport interface WalletRequester {\n request<T = unknown>(args: { method: string; params?: unknown[] }): Promise<T>;\n}\n\nconst textEncoder = new TextEncoder();\n\nfunction eip712DomainType(domain: TypedDataDomain): TypedDataField[] {\n const fields: TypedDataField[] = [];\n if (domain.name !== undefined) fields.push({ name: 'name', type: 'string' });\n if (domain.version !== undefined) fields.push({ name: 'version', type: 'string' });\n if (domain.chainId !== undefined) fields.push({ name: 'chainId', type: 'uint256' });\n if (domain.verifyingContract !== undefined) {\n fields.push({ name: 'verifyingContract', type: 'address' });\n }\n if (domain.salt !== undefined) fields.push({ name: 'salt', type: 'bytes32' });\n return fields;\n}\n\n/** The domain as JSON-RPC carries it: a numeric chain id as `0x` hex, a string one as written. */\nfunction serializeTypedDataDomain(domain: TypedDataDomain): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n if (domain.name !== undefined) result['name'] = domain.name;\n if (domain.version !== undefined) result['version'] = domain.version;\n if (domain.chainId !== undefined) {\n result['chainId'] =\n typeof domain.chainId === 'string' ? domain.chainId : `0x${domain.chainId.toString(16)}`;\n }\n if (domain.verifyingContract !== undefined) {\n result['verifyingContract'] = domain.verifyingContract;\n }\n if (domain.salt !== undefined) result['salt'] = domain.salt;\n return result;\n}\n\n/**\n * The JSON-RPC `eth_signTypedData_v4` payload: `EIP712Domain` FIRST in `types`, the primary type\n * the first key of `types`, the domain serialized for JSON-RPC.\n *\n * @example\n * ```typescript\n * buildTypedDataPayload({ name: 'Launchpad' }, { Message: [{ name: 'value', type: 'string' }] }, { value: 'hi' });\n * ```\n */\nexport function buildTypedDataPayload(\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n message: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n types: { EIP712Domain: eip712DomainType(domain), ...types },\n primaryType: Object.keys(types)[0],\n domain: serializeTypedDataDomain(domain),\n message,\n };\n}\n\n/**\n * A message as `personal_sign` carries it: `0x` plus the hex of its UTF-8 bytes (a lone surrogate\n * is encoded as U+FFFD, as every UTF-8 encoder does).\n *\n * @example\n * ```typescript\n * encodePersonalSignMessage('hello'); // '0x68656c6c6f'\n * ```\n */\nexport function encodePersonalSignMessage(message: string): string {\n return `0x${bytesToHex(textEncoder.encode(message))}`;\n}\n\nfunction signatureOf(value: unknown, scheme: string): string {\n if (typeof value !== 'string') throw new GalaSDKError('INVALID_SIGNATURE', { scheme });\n return value;\n}\n\n/** Asks a wallet for a `personal_sign` signature of `message` by `address`. */\nexport async function requestPersonalSignature(\n wallet: WalletRequester,\n address: string,\n message: string,\n): Promise<string> {\n const signature = await wallet.request<unknown>({\n method: 'personal_sign',\n params: [encodePersonalSignMessage(message), address],\n });\n return signatureOf(signature, 'personal-sign');\n}\n\n/** Asks a wallet for an `eth_signTypedData_v4` signature by `address`. */\nexport async function requestTypedDataSignature(\n wallet: WalletRequester,\n address: string,\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n message: Record<string, unknown>,\n): Promise<string> {\n const signature = await wallet.request<unknown>({\n method: 'eth_signTypedData_v4',\n params: [address, JSON.stringify(buildTypedDataPayload(domain, types, message))],\n });\n return signatureOf(signature, 'typed-data');\n}\n\n/** EIP-1193 codes for \"the wallet does not let this app use the account\". */\nconst UNAUTHORIZED = 4100;\n/** EIP-1193 codes for \"the wallet is disconnected\" (from every chain, from this chain). */\nconst DISCONNECTED: readonly unknown[] = [4900, 4901];\n\n/** What the provider operation was, for the error a wallet failure becomes. */\nexport type WalletOperation = 'connect' | 'personal_sign' | 'eth_signTypedData_v4';\n\n/** True when a wallet failure says the wallet is disconnected (the provider must forget it). */\nexport function isWalletDisconnection(code: number | string | undefined): boolean {\n return DISCONNECTED.includes(code);\n}\n\n/**\n * The core error a wallet's failure becomes, from its code (`code`, already parsed out of the\n * wallet's error) and the operation: an SDK error passes through; `4100` is `WALLET_NOT_CONNECTED`\n * (`unauthorized`), `4900` / `4901` `WALLET_NOT_CONNECTED` (`disconnected`); a decline\n * (`isWalletUserRejection`) is `WALLET_CONNECTION_FAILED` / `SIGNING_FAILED` with `user_rejected`;\n * anything else `failed`. The wallet's error is `cause` and its code `walletCode`.\n */\nexport function walletFailure(\n error: unknown,\n code: number | string | undefined,\n operation: WalletOperation,\n): SdkError {\n if (isGalaError(error)) return error;\n const context = { cause: error, walletCode: code ?? walletDeclineCode(error) };\n if (code === UNAUTHORIZED) {\n return new GalaSDKError('WALLET_NOT_CONNECTED', { reason: 'unauthorized', operation }, context);\n }\n if (isWalletDisconnection(code)) {\n return new GalaSDKError('WALLET_NOT_CONNECTED', { reason: 'disconnected', operation }, context);\n }\n const reason = code === 4001 || isWalletUserRejection(error) ? 'user_rejected' : 'failed';\n return operation === 'connect'\n ? new GalaSDKError('WALLET_CONNECTION_FAILED', { reason }, context)\n : new GalaSDKError('SIGNING_FAILED', { method: operation, reason }, context);\n}\n","/**\n * The connection state every wallet-backed provider shares (`ExternalWalletProvider`,\n * `GalaWalletProvider`): the account it signs for, the wallet events that move it, and the\n * listeners that follow it.\n *\n * Invariants (each tested in tests/providers.test.ts):\n *\n * - The wallet's events are listened to ONLY while connected: `connect()` subscribes once,\n * `disconnect()` and every wallet-side disconnection unsubscribe. A provider that was never\n * connected, or was disconnected, holds no listener on the wallet (no leak) and an\n * `accountsChanged` cannot connect it behind the app's back.\n * - The account and the spelling the wallet reported for it (`raw`, what Gala Wallet's\n * `setAddress` is handed) change together, in one assignment: they can never describe two\n * different accounts.\n * - An operation reads the connection ONCE, before its first await, and uses that snapshot for\n * every request it makes: a switch mid-operation cannot make one request name the old account\n * and the next the new one.\n * - A `connect()` that finishes after a later `disconnect()` does not connect (generation check).\n * - A `restore()` (the silent reconnect: `eth_accounts` only) is stricter: its answer is applied\n * only if nothing moved the account while the wallet answered (no `disconnect()`, wallet event or\n * `connect()` in between), because `eth_accounts` can be older than any of them.\n * - A chain change does not move the account (the identity is chain-independent); nothing here\n * caches a chain id that a `chainChanged` could make stale: the EIP-712 signers read the chain at\n * each signature.\n */\nimport { GalaSDKError, checksumEthereumAddress } from '../index.js';\nimport type { Eip1193Provider } from './types.js';\nimport {\n isWalletDisconnection,\n walletFailure,\n type SdkError,\n type WalletOperation,\n} from './wallet_requests.js';\n\n/** The account a provider is connected to: checksummed, and as the wallet reported it. */\nexport interface WalletAccount {\n /** `0x` plus the EIP-55 digits. */\n readonly address: string;\n /** The account exactly as the wallet reported it (`eth|...`, `0x...`, bare hex). */\n readonly raw: string;\n}\n\n/** A listener of the connected account: the new address, or `null` once disconnected. */\nexport type AccountListener = (address: string | null) => void;\n\n/**\n * Calls every account listener. A listener that throws is the app's bug: it is reported\n * asynchronously (an unhandled error the app's handler sees) and never breaks the provider's\n * state or the other listeners.\n */\nexport function notifyAccountListeners(\n listeners: ReadonlySet<AccountListener>,\n address: string | null,\n): void {\n for (const listener of [...listeners]) {\n try {\n listener(address);\n } catch (error: unknown) {\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n}\n\n/**\n * The base of a wallet-backed provider. Subclasses say how the wallet spells an account\n * (`accountOf`) and read the wallet's code off its errors (`walletCodeOf`).\n */\nexport abstract class WalletConnection<W extends Eip1193Provider> {\n protected readonly wallet: W;\n private account: WalletAccount | null = null;\n private generation = 0;\n /** Moves with every change of the account (set, switched, forgotten): a `restore()` in flight compares it. */\n private version = 0;\n private listening = false;\n private readonly listeners = new Set<AccountListener>();\n\n private readonly onAccountsChanged = (...args: unknown[]): void => {\n const accounts = args[0];\n const raw = Array.isArray(accounts) ? (accounts[0] as unknown) : undefined;\n const account = typeof raw === 'string' ? this.accountOf(raw) : undefined;\n // No account (or one the wallet spells in a way that is not an account) is a disconnection.\n if (account === undefined) {\n this.forget();\n return;\n }\n this.account = account;\n this.version += 1;\n this.notify(account.address);\n };\n\n private readonly onWalletDisconnect = (): void => {\n this.forget();\n };\n\n protected constructor(wallet: W | null | undefined) {\n if (wallet === null || wallet === undefined) {\n throw new GalaSDKError('INVALID_WALLET_PROVIDER_CONFIG', { missing: 'eip1193_provider' });\n }\n this.wallet = wallet;\n }\n\n /** The account `raw` names, or `undefined` when it does not name one. */\n protected abstract accountOf(raw: string): WalletAccount | undefined;\n\n /** The wallet's code on its error (an EIP-1193 number), when it carries one. */\n protected abstract walletCodeOf(error: unknown): number | string | undefined;\n\n /**\n * Asks the wallet for account access (`eth_requestAccounts`) and listens to its account and\n * disconnect events from then on.\n *\n * @returns The connected account (`0x`, checksummed).\n * @throws GalaSDKError `WALLET_CONNECTION_FAILED` (`no_accounts`, `user_rejected`, `failed`),\n * `WALLET_NOT_CONNECTED` (the wallet refused or is disconnected, or `disconnect()` was called\n * before the wallet answered).\n */\n public async connect(): Promise<string> {\n const generation = this.generation;\n let accounts: unknown;\n try {\n accounts = await this.wallet.request<unknown>({ method: 'eth_requestAccounts' });\n } catch (error: unknown) {\n throw this.failure(error, 'connect');\n }\n if (generation !== this.generation) {\n throw new GalaSDKError('WALLET_NOT_CONNECTED', {\n reason: 'not_connected',\n operation: 'connect',\n });\n }\n const raw = Array.isArray(accounts) ? (accounts[0] as unknown) : undefined;\n if (raw === undefined) {\n throw new GalaSDKError('WALLET_CONNECTION_FAILED', { reason: 'no_accounts' });\n }\n const account = typeof raw === 'string' ? this.accountOf(raw) : undefined;\n if (account === undefined) {\n throw new GalaSDKError(\n 'WALLET_CONNECTION_FAILED',\n { reason: 'failed' },\n { cause: new TypeError('the wallet reported an account that is not an Ethereum address') },\n );\n }\n this.adopt(account);\n return account.address;\n }\n\n /**\n * Reconnects to the account the wallet already lets this site use, WITHOUT a wallet prompt (for\n * the page reload after an earlier `connect()`): asks `eth_accounts` only, never\n * `eth_requestAccounts`. When the wallet reports an account the provider is connected to it and\n * listens to the wallet's events, exactly as after `connect()`; otherwise it stays not connected\n * and holds no listener.\n *\n * Nothing here throws. The wallet reporting no account, an account that is not an Ethereum\n * address, or `eth_accounts` failing all answer `null`: a silent restore that cannot happen is\n * not an error, the user connects with `connect()`. A `disconnect()`, a wallet event or a\n * `connect()` that lands while the wallet is answering wins over the answer (it may be older than\n * they are); the provider then answers its state at that moment.\n *\n * @returns The connected account (`0x`, checksummed), or `null` when not connected. Already\n * connected: the connected account, with no request.\n */\n public async restore(): Promise<string | null> {\n if (this.account !== null) return this.account.address;\n // Any disconnect, release, wallet event or connect moves `version`; see the class invariants.\n const version = this.version;\n let accounts: unknown;\n try {\n accounts = await this.wallet.request<unknown>({ method: 'eth_accounts' });\n } catch {\n return null;\n }\n if (version !== this.version) {\n return this.currentAddress();\n }\n const raw = Array.isArray(accounts) ? (accounts[0] as unknown) : undefined;\n const account = typeof raw === 'string' ? this.accountOf(raw) : undefined;\n if (account === undefined) return null;\n this.adopt(account);\n return account.address;\n }\n\n /** True while the provider has an account to sign for. */\n public isConnected(): boolean {\n return this.account !== null;\n }\n\n /**\n * The connected account (`0x`, checksummed).\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`.\n */\n public async getAddress(): Promise<string> {\n return this.requireAccount('getAddress').address;\n }\n\n /**\n * The connected account as GalaChain spells it (`eth|` plus the checksummed digits).\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`.\n */\n public async getGalaAddress(): Promise<string> {\n return `eth|${this.requireAccount('getGalaAddress').address.slice(2)}`;\n }\n\n /**\n * A wallet-backed provider never holds the key.\n *\n * @throws GalaSDKError `PRIVATE_KEY_NOT_ACCESSIBLE`, always.\n */\n public async getPrivateKey(): Promise<string> {\n throw new GalaSDKError('PRIVATE_KEY_NOT_ACCESSIBLE', {});\n }\n\n /**\n * Calls `listener` with the new account whenever it changes (`null` once disconnected).\n *\n * @returns The function that stops the calls.\n */\n public onAccountChanged(listener: AccountListener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** The wallet object the provider talks to. */\n public getProvider(): W {\n return this.wallet;\n }\n\n /**\n * Retires this provider object WITHOUT asking the wallet to end its session (unlike\n * `disconnect()`, which revokes / disconnects in the wallet): it forgets the account and removes\n * its listeners from the wallet. For code that drops a provider it created, so the wallet keeps\n * no listener of a provider nobody uses (the React context does it when it switches wallets).\n */\n public release(): void {\n this.disconnectLocally();\n }\n\n /** The connected account, read once by an operation before its first await. */\n protected requireAccount(operation: string): WalletAccount {\n if (this.account === null) {\n throw new GalaSDKError('WALLET_NOT_CONNECTED', { reason: 'not_connected', operation });\n }\n return this.account;\n }\n\n /** The core error a wallet failure becomes; a disconnection also forgets the account. */\n protected failure(error: unknown, operation: WalletOperation): SdkError {\n const code = this.walletCodeOf(error);\n if (isWalletDisconnection(code)) this.forget();\n return walletFailure(error, code, operation);\n }\n\n /** Forgets the account (an explicit disconnect also voids a `connect()` still in flight). */\n protected disconnectLocally(): void {\n this.generation += 1;\n this.forget();\n }\n\n /** The account of an `0x` / bare-hex spelling, checksummed; `undefined` for anything else. */\n protected static ethereumAccount(raw: string, spelled: string): WalletAccount | undefined {\n const address = checksumEthereumAddress(spelled);\n return address === undefined ? undefined : { address, raw };\n }\n\n /** The connected account's address now (a read after an await: not narrowed by an earlier check). */\n private currentAddress(): string | null {\n return this.account?.address ?? null;\n }\n\n /** Connects to `account`: remembers it, listens to the wallet, tells the listeners. */\n private adopt(account: WalletAccount): void {\n this.account = account;\n this.version += 1;\n this.listen();\n this.notify(account.address);\n }\n\n private forget(): void {\n this.unlisten();\n this.version += 1;\n if (this.account === null) return;\n this.account = null;\n this.notify(null);\n }\n\n private listen(): void {\n if (this.listening || typeof this.wallet.on !== 'function') return;\n this.wallet.on('accountsChanged', this.onAccountsChanged);\n this.wallet.on('disconnect', this.onWalletDisconnect);\n this.listening = true;\n }\n\n private unlisten(): void {\n if (!this.listening) return;\n this.listening = false;\n if (typeof this.wallet.removeListener !== 'function') return;\n this.wallet.removeListener('accountsChanged', this.onAccountsChanged);\n this.wallet.removeListener('disconnect', this.onWalletDisconnect);\n }\n\n private notify(address: string | null): void {\n notifyAccountListeners(this.listeners, address);\n }\n}\n","/**\n * An EIP-1193 browser wallet (MetaMask, Coinbase Wallet, Trust Wallet, ...) as a\n * {@link WalletProvider}. The key never leaves the wallet: every signature is the wallet's.\n */\nimport { BrowserWalletSigner, walletDeclineCode, type GalaChainSigner } from '../index.js';\nimport type {\n Eip1193Provider,\n TypedDataDomain,\n TypedDataField,\n WalletProvider,\n WalletProviderType,\n} from './types.js';\nimport { WalletConnection, type WalletAccount } from './wallet_connection.js';\nimport { requestPersonalSignature, requestTypedDataSignature } from './wallet_requests.js';\n\n/**\n * A browser wallet behind EIP-1193.\n *\n * @example\n * ```typescript\n * const provider = new ExternalWalletProvider(window.ethereum);\n * const address = await provider.connect();\n * const signature = await provider.signMessage('Hello');\n * await provider.disconnect();\n * ```\n */\nexport class ExternalWalletProvider\n extends WalletConnection<Eip1193Provider>\n implements WalletProvider\n{\n public readonly providerType: WalletProviderType = 'external';\n\n /**\n * @param provider - The wallet's EIP-1193 provider (`window.ethereum`, an EIP-6963 announcement).\n * @throws GalaSDKError `INVALID_WALLET_PROVIDER_CONFIG` when no provider is given.\n */\n public constructor(provider: Eip1193Provider) {\n super(provider);\n }\n\n protected accountOf(raw: string): WalletAccount | undefined {\n return WalletConnection.ethereumAccount(raw, raw);\n }\n\n protected walletCodeOf(error: unknown): number | string | undefined {\n return walletDeclineCode(error);\n }\n\n /**\n * Revokes the account permission where the wallet supports it (`wallet_revokePermissions`) and\n * forgets the account.\n */\n public async disconnect(): Promise<void> {\n this.disconnectLocally();\n try {\n await this.wallet.request({\n method: 'wallet_revokePermissions',\n params: [{ eth_accounts: {} }],\n });\n } catch {\n // Not every wallet implements wallet_revokePermissions; the provider is disconnected anyway.\n }\n }\n\n /**\n * Signs `message` with `personal_sign` (the wallet applies EIP-191).\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`, `SIGNING_FAILED`, `INVALID_SIGNATURE`.\n */\n public async signMessage(message: string): Promise<string> {\n const { address } = this.requireAccount('personal_sign');\n try {\n return await requestPersonalSignature(this.wallet, address, message);\n } catch (error: unknown) {\n throw this.failure(error, 'personal_sign');\n }\n }\n\n /**\n * Signs EIP-712 typed data with `eth_signTypedData_v4`.\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`, `SIGNING_FAILED`, `INVALID_SIGNATURE`.\n */\n public async signTypedData(\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n value: Record<string, unknown>,\n ): Promise<string> {\n const { address } = this.requireAccount('eth_signTypedData_v4');\n try {\n return await requestTypedDataSignature(this.wallet, address, domain, types, value);\n } catch (error: unknown) {\n throw this.failure(error, 'eth_signTypedData_v4');\n }\n }\n\n /**\n * The core {@link BrowserWalletSigner} for GalaChain DTOs, bound to the account connected now.\n *\n * @param options - `{ scheme: 'eip712' }` signs the EIP-712-capable DEX methods with\n * `eth_signTypedData_v4` (resolving a registered `client|` alias); the default is `personal_sign`.\n * `eip712DomainName` is the domain name those typed-data signatures carry (the deployment's:\n * `GALA_CHAIN_ENVIRONMENTS[env].eip712DomainName`; `ethereum` when absent).\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`.\n */\n public getSigner(\n options: { scheme?: 'personal-sign' | 'eip712'; eip712DomainName?: string | undefined } = {},\n ): GalaChainSigner {\n const { address } = this.requireAccount('getSigner');\n return new BrowserWalletSigner(this.wallet, address, options);\n }\n}\n","/**\n * Gala Wallet (the `window.gala` extension, or the same object from an EIP-6963 announcement) as a\n * {@link WalletProvider}. Gala Wallet holds one current account and is switched to the account a\n * signature is for with `setAddress` before every signature; its errors are JSON strings.\n */\nimport {\n GalaWalletSigner,\n walletDeclineCode,\n withGalaWalletIdentity,\n type GalaChainSigner,\n type GalaWalletScheme,\n} from '../index.js';\nimport type {\n Eip1193Provider,\n TypedDataDomain,\n TypedDataField,\n WalletProvider,\n WalletProviderType,\n} from './types.js';\nimport { WalletConnection, type WalletAccount } from './wallet_connection.js';\nimport { requestPersonalSignature, requestTypedDataSignature } from './wallet_requests.js';\n\n/** The Gala Wallet extension's API: EIP-1193 plus its account switch and disconnect. */\nexport interface GalaWalletExtension extends Eip1193Provider {\n /** Makes `address` the account the next request signs as. */\n setAddress?(address: string): Promise<void>;\n /** Ends the wallet's session with this app. */\n disconnect?(): Promise<void>;\n}\n\n/** An identity `GalaWalletSigner` accepts for `selectAddress` (`eth|`, `0x`, `client|`, 24 hex). */\nconst SELECTABLE_IDENTITY =\n /^(?:eth\\|[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\\|)?[0-9a-fA-F]{24})$/u;\n\n/**\n * The wallet's code on an error: Gala Wallet throws `Error`s whose message is a JSON object with a\n * numeric `code`; anything else is read as any wallet error is.\n */\nfunction galaWalletCode(error: unknown): number | string | undefined {\n if (error instanceof Error) {\n try {\n const parsed: unknown = JSON.parse(error.message);\n const code: unknown =\n typeof parsed === 'object' && parsed !== null\n ? (parsed as { code?: unknown }).code\n : undefined;\n if (typeof code === 'number') return code;\n } catch {\n // Not JSON: fall through to the error's own code.\n }\n }\n return walletDeclineCode(error);\n}\n\n/**\n * Gala Wallet as a wallet provider.\n *\n * @example\n * ```typescript\n * const provider = new GalaWalletProvider(window.gala);\n * const address = await provider.connect();\n * const signature = await provider.signMessage('Hello');\n * ```\n */\nexport class GalaWalletProvider\n extends WalletConnection<GalaWalletExtension>\n implements WalletProvider\n{\n public readonly providerType: WalletProviderType = 'external';\n\n /**\n * @param provider - Gala Wallet (`window.gala`, or its EIP-6963 announcement's provider).\n * @throws GalaSDKError `INVALID_WALLET_PROVIDER_CONFIG` when no provider is given.\n */\n public constructor(provider: GalaWalletExtension) {\n super(provider);\n }\n\n /**\n * Gala Wallet reports `eth|<40 hex>`, `0x<40 hex>` or the bare digits: all one account. An\n * `eth|0x...` is not an address form and is no account (`undefined`).\n */\n protected accountOf(raw: string): WalletAccount | undefined {\n if (/^eth\\|0[xX]/u.test(raw)) return undefined;\n return WalletConnection.ethereumAccount(raw, raw.startsWith('eth|') ? raw.slice(4) : raw);\n }\n\n protected walletCodeOf(error: unknown): number | string | undefined {\n return galaWalletCode(error);\n }\n\n /** Forgets the account and ends the wallet's session (`disconnect`, where it offers one). */\n public async disconnect(): Promise<void> {\n this.disconnectLocally();\n try {\n await this.wallet.disconnect?.();\n } catch {\n // The wallet's own disconnect failing leaves this provider disconnected anyway.\n }\n }\n\n /**\n * Signs `message` with `personal_sign`, after switching Gala Wallet to the connected account.\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`, `SIGNING_FAILED`, `INVALID_SIGNATURE`.\n */\n public async signMessage(message: string): Promise<string> {\n const { address, raw } = this.requireAccount('personal_sign');\n try {\n return await withGalaWalletIdentity(this.wallet, raw, () =>\n requestPersonalSignature(this.wallet, address, message),\n );\n } catch (error: unknown) {\n throw this.failure(error, 'personal_sign');\n }\n }\n\n /**\n * Signs EIP-712 typed data with `eth_signTypedData_v4`, after switching Gala Wallet to the\n * connected account.\n *\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`, `SIGNING_FAILED`, `INVALID_SIGNATURE`.\n */\n public async signTypedData(\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n value: Record<string, unknown>,\n ): Promise<string> {\n const { address, raw } = this.requireAccount('eth_signTypedData_v4');\n try {\n return await withGalaWalletIdentity(this.wallet, raw, () =>\n requestTypedDataSignature(this.wallet, address, domain, types, value),\n );\n } catch (error: unknown) {\n throw this.failure(error, 'eth_signTypedData_v4');\n }\n }\n\n /**\n * The core {@link GalaWalletSigner} for GalaChain DTOs, bound to the account connected now and\n * signing through this provider's wallet object.\n *\n * @param options - `{ scheme: 'personal-sign' }` opts into Gala Wallet's personal-sign scheme\n * (see `GalaWalletSigner`); the default is native signing.\n * @throws GalaSDKError `WALLET_NOT_CONNECTED`.\n */\n public getSigner(options: { scheme?: GalaWalletScheme } = {}): GalaChainSigner {\n const { address, raw } = this.requireAccount('getSigner');\n return new GalaWalletSigner(address, {\n scheme: options.scheme,\n selectAddress: SELECTABLE_IDENTITY.test(raw) ? raw : address,\n wallet: this.wallet,\n });\n }\n}\n","/**\n * A private key as a {@link WalletProvider}: signatures computed locally with core's secp256k1\n * primitives (no ethers), byte-identical to the ethers `Wallet` this provider wrapped before it\n * moved here (pinned by launchpad-sdk's `wallet-providers.golden.json`).\n */\nimport { bytesToHex } from '@noble/hashes/utils';\nimport {\n calculatePersonalSignPrefix,\n checksumEthereumAddress,\n ethAddressOfPrivateKey,\n GalaSDKError,\n isGalaError,\n normalizePrivateKey,\n PrivateKeySigner,\n signPersonalMessage,\n signTypedDataPayload,\n type GalaChainSigner,\n} from '../index.js';\nimport type {\n TypedDataDomain,\n TypedDataField,\n WalletProvider,\n WalletProviderType,\n} from './types.js';\nimport { notifyAccountListeners, type AccountListener } from './wallet_connection.js';\nimport type { SdkError } from './wallet_requests.js';\n\n/** The key spellings accepted: `0x` plus 64 hex digits, or the 64 digits (as ethers' `Wallet`). */\nconst KEY_SPELLING = /^(?:0x)?[0-9a-fA-F]{64}$/u;\n\n/** True when `message` has a lone UTF-16 surrogate: it has no UTF-8 encoding to sign. */\nfunction hasUnpairedSurrogate(message: string): boolean {\n for (let index = 0; index < message.length; index += 1) {\n const unit = message.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = message.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return true;\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * The domain fields that are set: ethers hashed only the fields that are not `null` /\n * `undefined`, and this provider signs exactly what it did.\n */\nfunction presentDomain(domain: TypedDataDomain): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(domain).filter(([, value]) => value !== undefined && value !== null),\n );\n}\n\n/** The core error a local signing failure becomes: an SDK error as it is, anything else `failed`. */\nfunction signingFailure(error: unknown, method: string): SdkError {\n return isGalaError(error)\n ? error\n : new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause: error });\n}\n\n/**\n * A wallet provider over a private key. Always ready to sign: `connect()` / `disconnect()` only\n * toggle `isConnected()`.\n *\n * @example\n * ```typescript\n * const provider = new PrivateKeyProvider(process.env.PRIVATE_KEY!);\n * const signature = await provider.signMessage('Hello');\n * const signer = provider.getSigner(); // native GalaChain signing\n * ```\n */\nexport class PrivateKeyProvider implements WalletProvider {\n public readonly providerType: WalletProviderType = 'privateKey';\n\n /** The key, `0x` plus 64 lower-case hex digits. Private: never enumerated or serialized. */\n readonly #privateKey: string;\n readonly #address: string;\n #connected = true;\n readonly #listeners = new Set<AccountListener>();\n\n /**\n * @param privateKey - `0x` plus 64 hex digits, or the 64 digits (any case).\n * @throws GalaSDKError `INVALID_PRIVATE_KEY` (`bad_encoding`, `not_on_curve`). The key is never\n * part of the error.\n */\n public constructor(privateKey: string) {\n if (typeof privateKey !== 'string' || !KEY_SPELLING.test(privateKey)) {\n throw new GalaSDKError('INVALID_PRIVATE_KEY', { reason: 'bad_encoding' });\n }\n const key = normalizePrivateKey(privateKey);\n try {\n this.#privateKey = `0x${bytesToHex(key)}`;\n // A derived address is always `0x` plus 40 lower-case hex digits, which always checksums.\n this.#address = checksumEthereumAddress(ethAddressOfPrivateKey(key)) as string;\n } finally {\n key.fill(0);\n }\n }\n\n /** A provider over the key an ethers `Wallet` (or any `{ privateKey }`) holds. */\n public static fromWallet(wallet: { readonly privateKey: string }): PrivateKeyProvider {\n return new PrivateKeyProvider(wallet.privateKey);\n }\n\n /**\n * Signs `message` as `personal_sign` does (EIP-191 over its UTF-8 bytes).\n *\n * @throws GalaSDKError `SIGNING_FAILED` for a message with a lone surrogate (it has no UTF-8\n * encoding; a wallet would sign U+FFFD instead of what was shown).\n */\n public async signMessage(message: string): Promise<string> {\n try {\n if (hasUnpairedSurrogate(message)) {\n throw new TypeError('the message has a lone UTF-16 surrogate, which has no UTF-8 encoding');\n }\n const key = normalizePrivateKey(this.#privateKey);\n try {\n return `0x${signPersonalMessage(key, calculatePersonalSignPrefix(message), message)}`;\n } finally {\n key.fill(0);\n }\n } catch (error: unknown) {\n throw signingFailure(error, 'personal_sign');\n }\n }\n\n /**\n * Signs EIP-712 typed data (`eth_signTypedData_v4`) with core's encoder, which fails closed on a\n * value ethers would have coerced (`TYPED_DATA_*`).\n *\n * @throws GalaSDKError `TYPED_DATA_*` for typed data the encoder refuses, `SIGNING_FAILED`.\n */\n public async signTypedData(\n domain: TypedDataDomain,\n types: Record<string, TypedDataField[]>,\n value: Record<string, unknown>,\n ): Promise<string> {\n try {\n return await signTypedDataPayload(this.#privateKey, {\n domain: presentDomain(domain),\n types,\n message: value,\n });\n } catch (error: unknown) {\n throw signingFailure(error, 'eth_signTypedData_v4');\n }\n }\n\n /** The key's account: `0x` plus the EIP-55 digits. */\n public async getAddress(): Promise<string> {\n return this.#address;\n }\n\n /** The key's account as GalaChain spells it: `eth|` plus the EIP-55 digits. */\n public async getGalaAddress(): Promise<string> {\n return `eth|${this.#address.slice(2)}`;\n }\n\n /** The core {@link PrivateKeySigner} (native GalaChain signing) over this key. */\n public getSigner(): GalaChainSigner {\n return new PrivateKeySigner(this.#privateKey);\n }\n\n /** Marks the provider connected (it always can sign) and returns its account. */\n public async connect(): Promise<string> {\n this.#connected = true;\n this.#notify(this.#address);\n return this.#address;\n }\n\n /** Marks the provider disconnected; it can still sign. */\n public async disconnect(): Promise<void> {\n this.#connected = false;\n this.#notify(null);\n }\n\n /** True until `disconnect()` (again after `connect()`). */\n public isConnected(): boolean {\n return this.#connected;\n }\n\n /** The key: `0x` plus 64 lower-case hex digits. */\n public async getPrivateKey(): Promise<string> {\n return this.#privateKey;\n }\n\n /**\n * The key, synchronously: `0x` plus 64 lower-case hex digits. For code that must build its own\n * signer from it (an ethers `Wallet`) in a synchronous path.\n */\n public exportPrivateKey(): string {\n return this.#privateKey;\n }\n\n /**\n * Calls `listener` with the account on `connect()` and `null` on `disconnect()`.\n *\n * @returns The function that stops the calls.\n */\n public onAccountChanged(listener: AccountListener): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #notify(address: string | null): void {\n notifyAccountListeners(this.#listeners, address);\n }\n}\n","/**\n * Browser wallet detection: EIP-6963 announcements, with the injected globals as a fallback\n * (`window.ethereum`, Trust Wallet behind another wallet, `window.gala`).\n *\n * Safe everywhere: without a browser window (Node, SSR, React Native, an MV3 service worker) every\n * function returns \"nothing found\" and nothing throws. Announcements are read structurally and a\n * malformed one is ignored, never trusted.\n */\nimport type {\n DetectedWallet,\n Eip1193Provider,\n Eip6963ProviderInfo,\n WalletDetectionResult,\n} from './types.js';\n\n/** The reverse-DNS ids of well-known wallets. */\nexport const KNOWN_WALLET_RDNS = {\n METAMASK: 'io.metamask',\n METAMASK_FLASK: 'io.metamask.flask',\n COINBASE: 'com.coinbase.wallet',\n TRUST_WALLET: 'com.trustwallet.app',\n PHANTOM: 'app.phantom',\n RAINBOW: 'me.rainbow',\n OKX: 'com.okex.wallet',\n RABBY: 'io.rabby',\n BRAVE: 'com.brave.wallet',\n FRAME: 'sh.frame',\n LEDGER: 'com.ledger',\n ZERION: 'io.zerion.wallet',\n GALA: 'com.gala.wallet',\n} as const;\n\n/** Default icons (data URIs) of known wallets, used when a wallet announces none. */\nconst DEFAULT_WALLET_ICONS: Readonly<Record<string, string>> = {\n [KNOWN_WALLET_RDNS.METAMASK]:\n 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIxLjU0IDQuMjJsLTguMzQgNi4yMSAxLjU0LTMuNjUtLTUuNTMtMi41MXoiIGZpbGw9IiNFMjc2MUIiLz48L3N2Zz4=',\n [KNOWN_WALLET_RDNS.GALA]:\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAYAAACoYAD2AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAjWSURBVHgBzZkLVI1ZG8f/pZKjq0uK0LglIiMKU5EuBkMxUgmjL6GFSZJ7QpJx+Ujpk1Eat3KJySXjTnIpVJRPhnTSxWVaSveL1Zlnv3WshnM67wlrzX+t3T5nv3vv99d+9/O8z36OAj5DIpGoM1W2VPSp6FJp03ipmkoRlVwq9xUUFDLwGVKCnCKwAVRNqa2rc8vOLeiRkpqpcO/hY7woeI3yikrUva9DG1VV6HXqiJHDv0Uvg66oqa0VqigrX6dxUQScCDmlwLcjwfWjKuhJdq5jVMwpxMRfQP7LN7zGttPWxARbC3i4OsDCzOQuNQUS7GnwlExIgmtH1ea0zCfugdsjFeMvJLI2tFSmA/sieMV82Fqa/UFfvQhWKGuMgg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3RAKE9tpeNj4btZQb8tZ92SPpbBzWcj73M0C4DU+s4X08RNrkpTBYA7xhrf/tj6h+45CHhn27M7lKCsoyGhu332sQcZ9kBgXUazWVmBKq5gDWZCNoAaUTUugk54RiwG/puzo9Bm5zb+MTqRsH96U1Ke5rBrzL/E7I48MXkFWXVVdgy+txXPdsHG5F8sC2xOg1BOdrPwke734ZQvzV09fuAbJaY/wJdRFVwcRvyzHOJvvLtPXaQTYbMqYVzqaYCdQ2UFZ3h6U7QVlfdESMec/d8Yk+M51e01gLCcZzmcc75x5I+wMquanZz4xjz52FiyhzwIJ5uglSYlSKz0IzMJ8ENwoUrccNjhLSVHxAF0KI8BS8JRckE1gzamyp/J94auiITl5BSpvS0rJsqu4Xx8E9OsDi9D19TrVUyovh+KFOOp7nsptgpM7Em4R5EfArdDwOw5L7rAsATvcFVMRskJQsr24DP0NVvGaoREi2pYAAAAASUVORK5CYII=',\n};\n\n/** The parts of a browser window detection uses (structural: no DOM types). */\ninterface BrowserWindow {\n addEventListener(type: string, listener: (event: unknown) => void): void;\n removeEventListener(type: string, listener: (event: unknown) => void): void;\n dispatchEvent(event: unknown): boolean;\n Event?: new (type: string) => unknown;\n ethereum?: unknown;\n gala?: unknown;\n trustwallet?: unknown;\n trustWallet?: unknown;\n}\n\nconst ANNOUNCE = 'eip6963:announceProvider';\nconst REQUEST = 'eip6963:requestProvider';\n/** The window event Trust Wallet fires once its provider is injected (it can be after page load). */\nconst TRUST_INITIALIZED = 'trustwallet#initialized';\n/** How long {@link getTrustWallet} waits for {@link TRUST_INITIALIZED} by default. */\nconst TRUST_INIT_WAIT_MS = 3000;\n\n/** The browser window, or `undefined` outside a browser (no `window`, or one that cannot dispatch). */\nfunction browserWindow(): BrowserWindow | undefined {\n const candidate: unknown = (globalThis as { window?: unknown }).window;\n if (typeof candidate !== 'object' || candidate === null) return undefined;\n const window = candidate as Partial<BrowserWindow>;\n return typeof window.dispatchEvent === 'function' &&\n typeof window.addEventListener === 'function' &&\n typeof window.removeEventListener === 'function'\n ? (candidate as BrowserWindow)\n : undefined;\n}\n\n/** An EIP-1193 provider with the identity flags injected wallets set on themselves. */\ntype TrustCandidate = Eip1193Provider & { isTrust?: boolean; isMetaMask?: boolean };\n\nfunction isRequestable(candidate: unknown): candidate is TrustCandidate {\n return (\n typeof candidate === 'object' &&\n candidate !== null &&\n typeof (candidate as { request?: unknown }).request === 'function'\n );\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n/** An EIP-6963 announcement read: the wallet it describes and the announcement's uuid. */\ninterface Announcement {\n readonly wallet: DetectedWallet;\n readonly uuid: string;\n}\n\n/** The wallet an EIP-6963 announcement describes, or `undefined` for a malformed one. */\nfunction announcement(event: unknown): Announcement | undefined {\n const detail: unknown =\n typeof event === 'object' && event !== null\n ? (event as { detail?: unknown }).detail\n : undefined;\n if (typeof detail !== 'object' || detail === null) return undefined;\n const { info, provider } = detail as { info?: unknown; provider?: unknown };\n if (typeof info !== 'object' || info === null || !isRequestable(provider)) return undefined;\n const { uuid, name, icon, rdns } = info as Partial<Record<keyof Eip6963ProviderInfo, unknown>>;\n if (!isString(uuid) || !isString(name)) return undefined;\n const id = isString(rdns) && rdns !== '' ? rdns : uuid;\n const wallet: DetectedWallet = {\n id,\n name,\n rdns: id,\n icon: isString(icon) ? icon : (DEFAULT_WALLET_ICONS[isString(rdns) ? rdns : ''] ?? ''),\n provider,\n isInjected: false,\n };\n return { wallet, uuid };\n}\n\n/**\n * Asks every EIP-6963 wallet to announce itself (when the environment can build the event). The\n * event is built with the WINDOW's own `Event` (in a browser the same as the global one): an event\n * from another realm (a test DOM, an iframe) is refused by `dispatchEvent`.\n */\nfunction requestAnnouncements(window: BrowserWindow): void {\n const EventConstructor =\n window.Event ?? (globalThis as { Event?: new (type: string) => unknown }).Event;\n if (typeof EventConstructor === 'function') window.dispatchEvent(new EventConstructor(REQUEST));\n}\n\n/** The injected `window.ethereum` when it is an EIP-1193 provider. */\nfunction injectedProvider(window: BrowserWindow | undefined): TrustCandidate | undefined {\n const ethereum = window?.ethereum;\n return isRequestable(ethereum) ? ethereum : undefined;\n}\n\n/**\n * Trust Wallet's injected provider, also when another wallet owns `window.ethereum`: it can sit in\n * the non-standard `window.ethereum.providers` array or only in its own `window.trustwallet`.\n */\nfunction trustWalletProvider(window: BrowserWindow): Eip1193Provider | undefined {\n const ethereum = injectedProvider(window);\n if (ethereum?.isTrust === true) return ethereum;\n const providers: unknown =\n typeof window.ethereum === 'object' && window.ethereum !== null\n ? (window.ethereum as { providers?: unknown }).providers\n : undefined;\n if (Array.isArray(providers)) {\n const found: unknown = providers.find(\n (candidate: unknown) => isRequestable(candidate) && candidate.isTrust === true,\n );\n if (isRequestable(found)) return found;\n }\n if (isRequestable(window.trustwallet)) return window.trustwallet;\n // The camel-cased global is read as a fallback, and only when it says it is Trust Wallet.\n const camel: unknown = window.trustWallet;\n return isRequestable(camel) && camel.isTrust === true ? camel : undefined;\n}\n\n/** True for a provider that is MetaMask itself: it says so, and is not Trust Wallet posing as it. */\nfunction isMetaMaskProvider(provider: unknown): boolean {\n return isRequestable(provider) && provider.isMetaMask === true && provider.isTrust !== true;\n}\n\n/** True for a provider that says it is Trust Wallet. */\nfunction isTrustProvider(provider: unknown): boolean {\n return isRequestable(provider) && provider.isTrust === true;\n}\n\n/**\n * MetaMask's injected provider: `window.ethereum` when it is MetaMask, else the MetaMask entry of\n * the non-standard `window.ethereum.providers` array a multi-wallet browser keeps. Never Trust\n * Wallet, which sets `isMetaMask` on itself too.\n */\nfunction injectedMetaMask(window: BrowserWindow): Eip1193Provider | undefined {\n const ethereum = injectedProvider(window);\n if (ethereum === undefined) return undefined;\n if (isMetaMaskProvider(ethereum)) return ethereum;\n const providers: unknown = (ethereum as { providers?: unknown }).providers;\n if (!Array.isArray(providers)) return undefined;\n const found: unknown = providers.find(isMetaMaskProvider);\n return isRequestable(found) ? found : undefined;\n}\n\nfunction injectedWallet(id: string, name: string, provider: Eip1193Provider): DetectedWallet {\n return { id, name, rdns: id, icon: DEFAULT_WALLET_ICONS[id] ?? '', provider, isInjected: true };\n}\n\n/** The injected wallets, as the fallback after the announcement window closed. */\nfunction injectedFallback(window: BrowserWindow, found: DetectedWallet[]): DetectedWallet[] {\n const wallets = [...found];\n const has = (id: string): boolean => wallets.some((wallet) => wallet.id === id);\n const ethereum = injectedProvider(window);\n if (wallets.length === 0 && ethereum !== undefined) {\n const flags = ethereum as { isCoinbaseWallet?: boolean };\n if (isMetaMaskProvider(ethereum)) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.METAMASK, 'MetaMask', ethereum));\n } else if (flags.isCoinbaseWallet === true) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.COINBASE, 'Coinbase Wallet', ethereum));\n } else if (ethereum.isTrust === true) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.TRUST_WALLET, 'Trust Wallet', ethereum));\n } else {\n wallets.push(injectedWallet('injected', 'Browser Wallet', ethereum));\n }\n }\n // MetaMask behind another wallet (the multi-injection `providers` array), unless a MetaMask is\n // already listed: by its rdns, or as an announcement that says `isMetaMask` (Rabby and Brave do).\n const metamask = injectedMetaMask(window);\n if (\n metamask !== undefined &&\n !wallets.some(\n (wallet) =>\n wallet.id === KNOWN_WALLET_RDNS.METAMASK ||\n wallet.id === KNOWN_WALLET_RDNS.METAMASK_FLASK ||\n isMetaMaskProvider(wallet.provider),\n )\n ) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.METAMASK, 'MetaMask', metamask));\n }\n // Trust Wallet is listed once, also when it announced under another rdns but says `isTrust`.\n if (\n !has(KNOWN_WALLET_RDNS.TRUST_WALLET) &&\n !wallets.some((wallet) => isTrustProvider(wallet.provider))\n ) {\n const trust = trustWalletProvider(window);\n if (trust !== undefined && !wallets.some((wallet) => wallet.provider === trust)) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.TRUST_WALLET, 'Trust Wallet', trust));\n }\n }\n if (isRequestable(window.gala) && !has(KNOWN_WALLET_RDNS.GALA)) {\n wallets.push(injectedWallet(KNOWN_WALLET_RDNS.GALA, 'Gala Wallet', window.gala));\n }\n return wallets;\n}\n\nfunction resultOf(wallets: DetectedWallet[]): WalletDetectionResult {\n return {\n wallets,\n byId: new Map(wallets.map((wallet) => [wallet.id, wallet])),\n hasWallets: wallets.length > 0,\n ...(wallets[0] === undefined ? {} : { primary: wallets[0] }),\n };\n}\n\n/**\n * The wallets in this browser: every EIP-6963 announcement within `timeout` ms (one per uuid),\n * then the injected fallbacks (`window.ethereum` when nothing announced, Trust Wallet, Gala Wallet).\n * Outside a browser it resolves to \"nothing found\" at once.\n *\n * @example\n * ```typescript\n * const { wallets, primary } = await detectWallets();\n * if (primary) await new ExternalWalletProvider(primary.provider).connect();\n * ```\n */\nexport async function detectWallets(timeout: number = 500): Promise<WalletDetectionResult> {\n const window = browserWindow();\n if (window === undefined) return resultOf([]);\n\n return new Promise((resolve) => {\n const wallets: DetectedWallet[] = [];\n const seen = new Set<string>();\n const onAnnounce = (event: unknown): void => {\n const announced = announcement(event);\n // Some wallets announce more than once: one entry per announcement uuid.\n if (announced === undefined || seen.has(announced.uuid)) return;\n seen.add(announced.uuid);\n wallets.push(announced.wallet);\n };\n window.addEventListener(ANNOUNCE, onAnnounce);\n requestAnnouncements(window);\n setTimeout(() => {\n window.removeEventListener(ANNOUNCE, onAnnounce);\n resolve(resultOf(injectedFallback(window, wallets)));\n }, timeout);\n });\n}\n\n/**\n * Calls `callback` with the detected wallets now and again whenever a new wallet announces itself.\n * Outside a browser it never calls and the returned function does nothing.\n *\n * @returns The function that stops the calls and the listening.\n */\nexport function subscribeToWalletChanges(\n callback: (result: WalletDetectionResult) => void,\n): () => void {\n const window = browserWindow();\n if (window === undefined) return () => undefined;\n\n let subscribed = true;\n let current: DetectedWallet[] = [];\n const onAnnounce = (event: unknown): void => {\n const wallet = announcement(event)?.wallet;\n if (!subscribed || wallet === undefined || current.some((known) => known.id === wallet.id)) {\n return;\n }\n current = [...current, wallet];\n callback(resultOf(current));\n };\n window.addEventListener(ANNOUNCE, onAnnounce);\n void detectWallets().then((result) => {\n if (!subscribed) return;\n current = result.wallets;\n callback(result);\n });\n return () => {\n subscribed = false;\n window.removeEventListener(ANNOUNCE, onAnnounce);\n };\n}\n\n/** The detected wallet with reverse-DNS id `rdns`, or `null`. */\nexport async function getWalletByRdns(\n rdns: string,\n timeout?: number,\n): Promise<DetectedWallet | null> {\n const result = await detectWallets(timeout);\n return result.byId.get(rdns) ?? null;\n}\n\n/** True when the wallet with reverse-DNS id `rdns` is detected. */\nexport async function isWalletAvailable(rdns: string, timeout?: number): Promise<boolean> {\n return (await getWalletByRdns(rdns, timeout)) !== null;\n}\n\n/**\n * MetaMask among detected wallets, in this order: an announcement with rdns `io.metamask` or\n * `io.metamask.flask`; else any listed provider that says `isMetaMask` and is not `isTrust` (an\n * announcement, `window.ethereum`, or its `providers[]` entry; Trust Wallet sets `isMetaMask` on\n * itself, and is never returned here); else `undefined`.\n *\n * It is a lookup, not a relabelling: `detectWallets` still lists a wallet that announces itself as\n * Rabby or Brave (which also say `isMetaMask`) under its own rdns.\n */\nexport function findMetaMaskWallet(result: WalletDetectionResult): DetectedWallet | undefined {\n return (\n result.wallets.find(\n (wallet) =>\n wallet.id === KNOWN_WALLET_RDNS.METAMASK || wallet.id === KNOWN_WALLET_RDNS.METAMASK_FLASK,\n ) ?? result.wallets.find((wallet) => isMetaMaskProvider(wallet.provider))\n );\n}\n\n/**\n * Trust Wallet among detected wallets: the listed wallet with rdns `com.trustwallet.app`, else any\n * listed provider that says `isTrust` (an announcement under another rdns, `window.ethereum`, its\n * `providers[]` entry), else `undefined`.\n */\nexport function findTrustWallet(result: WalletDetectionResult): DetectedWallet | undefined {\n return result.wallets.find(\n (wallet) => wallet.id === KNOWN_WALLET_RDNS.TRUST_WALLET || isTrustProvider(wallet.provider),\n );\n}\n\n/** MetaMask in this browser (see {@link findMetaMaskWallet}), or `null`. */\nexport async function getMetaMaskWallet(timeout?: number): Promise<DetectedWallet | null> {\n return findMetaMaskWallet(await detectWallets(timeout)) ?? null;\n}\n\n/** Resolves when `window` fires {@link TRUST_INITIALIZED} or after `timeout` ms, whichever is first. */\nfunction trustInitialized(window: BrowserWindow, timeout: number): Promise<void> {\n return new Promise((resolve) => {\n const done = (): void => {\n clearTimeout(timer);\n window.removeEventListener(TRUST_INITIALIZED, done);\n resolve();\n };\n // `done` runs only after both lines below (an event or the timer), never inside them.\n window.addEventListener(TRUST_INITIALIZED, done);\n const timer = setTimeout(done, timeout);\n });\n}\n\n/**\n * Trust Wallet in this browser (see {@link findTrustWallet}; also `window.trustwallet` /\n * `window.trustWallet`). Trust Wallet can inject after the page loaded, so when it is not found at\n * once this waits up to `options.timeout` ms (default 3000) for its `trustwallet#initialized`\n * window event and looks again; it never waits when the wallet is already there. Resolves `null`\n * when it is not found, and at once without a browser window.\n *\n * @param options - `timeout`: the most to wait for the initialized event; `announceTimeout`: the\n * EIP-6963 announcement window of the first look (see {@link detectWallets}).\n */\nexport async function getTrustWallet(\n options: { timeout?: number; announceTimeout?: number } = {},\n): Promise<DetectedWallet | null> {\n const found = findTrustWallet(await detectWallets(options.announceTimeout));\n if (found !== undefined) return found;\n const window = browserWindow();\n if (window === undefined) return null;\n await trustInitialized(window, options.timeout ?? TRUST_INIT_WAIT_MS);\n return findTrustWallet(await detectWallets(0)) ?? null;\n}\n\n/** True at once (no waiting) when an injected `window.ethereum` provider exists. */\nexport function hasAnyWallet(): boolean {\n return injectedProvider(browserWindow()) !== undefined;\n}\n\n/** The injected `window.ethereum` provider, or `null` (also outside a browser). */\nexport function getInjectedEip1193Provider(): Eip1193Provider | null {\n return injectedProvider(browserWindow()) ?? null;\n}\n","/**\n * Building and inspecting wallet providers.\n */\nimport { GalaSDKError } from '../index.js';\nimport { ExternalWalletProvider } from './external_wallet_provider.js';\nimport { PrivateKeyProvider } from './private_key_provider.js';\nimport type { Eip1193Provider, WalletProvider, WalletProviderConfig } from './types.js';\n\n/**\n * The provider a config describes: a {@link PrivateKeyProvider} for a non-empty `privateKey`\n * (preferred when both are given), else an {@link ExternalWalletProvider} for `eip1193Provider`.\n *\n * @throws GalaSDKError `INVALID_WALLET_PROVIDER_CONFIG` when the config has neither,\n * `INVALID_PRIVATE_KEY` for a key that is not one.\n *\n * @example\n * ```typescript\n * const provider = createWalletProvider({ eip1193Provider: window.ethereum });\n * await provider.connect();\n * ```\n */\nexport function createWalletProvider(config: WalletProviderConfig): WalletProvider {\n if (config.privateKey !== undefined && config.privateKey.length > 0) {\n return new PrivateKeyProvider(config.privateKey);\n }\n if (config.eip1193Provider !== undefined && config.eip1193Provider !== null) {\n return new ExternalWalletProvider(config.eip1193Provider);\n }\n throw new GalaSDKError('INVALID_WALLET_PROVIDER_CONFIG', {\n missing: 'private_key_or_eip1193_provider',\n });\n}\n\n/** An {@link ExternalWalletProvider} over an EIP-1193 provider. */\nexport function createProviderFromEip1193(provider: Eip1193Provider): ExternalWalletProvider {\n return new ExternalWalletProvider(provider);\n}\n\n/** True for a provider that holds a raw key (a {@link PrivateKeyProvider}). */\nexport function isPrivateKeyProvider(provider: WalletProvider): provider is PrivateKeyProvider {\n return provider.providerType === 'privateKey' && provider instanceof PrivateKeyProvider;\n}\n\n/** True for a provider that signs in a wallet. */\nexport function isExternalProvider(provider: WalletProvider): boolean {\n return provider.providerType === 'external';\n}\n\n/** The provider's raw key when it has one, else `undefined` (never throws). */\nexport async function getPrivateKeyIfAvailable(\n provider: WalletProvider,\n): Promise<string | undefined> {\n if (!isPrivateKeyProvider(provider)) return undefined;\n return provider.getPrivateKey();\n}\n\n/** The connected account, connecting first when the provider is not connected. */\nexport async function ensureConnected(provider: WalletProvider): Promise<string> {\n return provider.isConnected() ? provider.getAddress() : provider.connect();\n}\n\n/** True for an object with an EIP-1193 `request` method. */\nexport function isEip1193Provider(value: unknown): value is Eip1193Provider {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { request?: unknown }).request === 'function'\n );\n}\n"],"mappings":"A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