@babylonlabs-io/wallet-connector 2.0.13 → 2.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ETHWalletProvider-CjaxIpOZ.js → ETHWalletProvider-Dq5EwVtB.js} +3 -3
- package/dist/{ETHWalletProvider-CjaxIpOZ.js.map → ETHWalletProvider-Dq5EwVtB.js.map} +1 -1
- package/dist/{ETHWalletProvider-DtY9fxP-.cjs → ETHWalletProvider-wp9s8vtc.cjs} +2 -2
- package/dist/{ETHWalletProvider-DtY9fxP-.cjs.map → ETHWalletProvider-wp9s8vtc.cjs.map} +1 -1
- package/dist/eth.cjs +1 -1
- package/dist/eth.es.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.es.js +2 -2
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ETHWalletProvider-CjaxIpOZ.js","sources":["../../../node_modules/.pnpm/vite-plugin-node-polyfills@0.23.0_rollup@4.46.1_vite@6.4.1_@types+node@22.17.0_jiti@2.5_590787783d08c931a0b9f4ec9ff54180/node_modules/vite-plugin-node-polyfills/shims/process/dist/index.js","../src/constants/walletEvents.ts","../src/constants/index.ts","../src/core/Wallet.ts","../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js","../src/error/codes.ts","../src/error/index.ts","../src/core/WalletConnector.ts","../src/core/types.ts","../src/core/index.ts","../src/hooks/redetectReconnect.ts","../src/hooks/useWalletRedetection.ts","../src/hooks/usePersistState.ts","../src/context/Inscriptions.context.tsx","../src/core/confirmationReceipt.ts","../src/context/State.context.tsx","../src/context/Chain.context.tsx","../src/context/LifecycleHooks.context.tsx","../src/core/storage.ts","../src/core/wallets/constants.ts","../src/core/wallets/icons/okx.svg","../src/core/wallets/appkit/constants.ts","../src/core/wallets/appkit/state.ts","../src/core/wallets/eth/appkit/sharedConfig.ts","../src/core/wallets/eth/appkit/provider.ts","../src/core/wallets/eth/appkit/index.ts","../src/core/wallets/eth/icon.svg","../src/core/wallets/eth/index.ts","../src/core/wallets/eth/appkit/modal.ts","../src/hooks/appkit/useAppKitOpenListener.ts","../src/hooks/useChainConnector.ts","../src/core/wallets/firstPartyIcons.ts","../src/hooks/useWidgetState.ts","../src/hooks/useWalletConnectors.tsx","../src/hooks/useWalletWidgets.tsx","../src/hooks/useWalletConnect.ts","../src/components/ChainButton/index.tsx","../src/components/ConnectedWallet/index.tsx","../src/components/Chains/index.tsx","../src/components/Chains/container.tsx","../src/components/Error/index.tsx","../src/components/Error/container.tsx","../src/components/Loader/index.tsx","../src/components/WalletButton/index.tsx","../src/components/Wallets/index.tsx","../src/components/Wallets/container.tsx","../src/components/WalletProvider/components/Screen.tsx","../src/components/WalletProvider/components/WalletDialog.tsx","../src/hooks/useVisibilityCheck.ts","../src/providers/ETHWalletProvider.tsx"],"sourcesContent":["function getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar browser = {exports: {}};\n\n// shim for using process in browser\nvar process = browser.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ());\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] };\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\nvar browserExports = browser.exports;\nconst process$1 = /*@__PURE__*/getDefaultExportFromCjs(browserExports);\n\nexport { process$1 as default, process$1 as process };\n//# sourceMappingURL=index.js.map\n","/**\n * Wallet event name constants\n *\n * Different wallets use different event names for the same events.\n * These constants help normalize event handling across wallets.\n */\n\n/** Event names for account changes (different wallets use different names) */\nexport const ACCOUNT_CHANGE_EVENTS = [\"accountChanged\", \"accountsChanged\"] as const;\n\nexport type AccountChangeEvent = (typeof ACCOUNT_CHANGE_EVENTS)[number];\n\n/** Check if an event name is an account change event */\nexport function isAccountChangeEvent(eventName: string): eventName is AccountChangeEvent {\n return ACCOUNT_CHANGE_EVENTS.includes(eventName as AccountChangeEvent);\n}\n\nexport const NETWORK_CHANGE_EVENT = \"networkChanged\" as const;\n\n/** Event name for disconnect */\nexport const DISCONNECT_EVENT = \"disconnect\" as const;\n\nexport function trackProviderIdentityChanges(\n provider: { on?: (event: string, callback: () => void) => void },\n callback: () => void,\n): boolean {\n if (typeof provider.on !== \"function\") return false;\n\n try {\n provider.on(\"accountsChanged\", callback);\n } catch {\n return false;\n }\n\n [NETWORK_CHANGE_EVENT, DISCONNECT_EVENT].forEach((event) => {\n try {\n provider.on?.(event, callback);\n } catch {\n // Some wallet providers reject event names that they do not support.\n }\n });\n\n return true;\n}\n\n/**\n * Window event dispatched when the wallet-selection modal opens.\n *\n * Late-injection re-detection (`useWalletRedetection`) listens for this so a\n * wallet whose extension injected after the initial detection — and after the\n * fallback timeout — is still re-detected by the time the user actually opens\n * the modal, flipping it from a download link to a connect button.\n */\nexport const WALLET_MODAL_OPEN_EVENT = \"babylon-wallet#modal-open\" as const;\n\n/** Cosmos wallet keystore change events (different wallets use different window events) */\nexport const COSMOS_KEYSTORE_CHANGE_EVENTS = [\n \"keplr_keystorechange\",\n \"leap_keystorechange\",\n \"okx_keystorechange\",\n] as const;\n\n/**\n * Helper to remove event listener from a provider.\n * Falls back from removeListener to off for compatibility across wallet implementations.\n */\nexport function removeProviderListener(\n provider: { removeListener?: (event: string, cb: () => void) => void; off?: (event: string, cb: () => void) => void },\n event: string,\n callback: () => void,\n): void {\n if (typeof provider.removeListener === \"function\") {\n provider.removeListener(event, callback);\n } else if (typeof provider.off === \"function\") {\n provider.off(event, callback);\n }\n}\n","export * from \"./walletEvents\";\n\n/** Default account-storage lifetime. */\nexport const ONE_HOUR = 60 * 60 * 1000;\n","import type { Account, IProvider, IWallet, Network, ProgressReporter } from \"@/core/types\";\n\nexport interface WalletOptions<P extends IProvider> {\n id: string;\n name: string;\n icon: string;\n iconBackground?: string;\n docs: string;\n networks: Network[];\n origin: any;\n provider: P | null;\n label?: string;\n hardware?: boolean;\n}\n\nexport class Wallet<P extends IProvider> implements IWallet {\n readonly id: string;\n readonly origin: any;\n readonly name: string;\n readonly icon: string;\n readonly iconBackground?: string;\n readonly docs: string;\n readonly networks: Network[];\n readonly provider: P | null = null;\n readonly hardware: boolean;\n private readonly _label?: string;\n account: Account | null = null;\n\n constructor({ id, origin, name, icon, iconBackground, docs, networks, provider, label, hardware }: WalletOptions<P>) {\n this.id = id;\n this.origin = origin;\n this.name = name;\n this.icon = icon;\n this.iconBackground = iconBackground;\n this.docs = docs;\n this.networks = networks;\n this.provider = provider;\n this._label = label;\n this.hardware = hardware ?? false;\n }\n\n get installed() {\n return Boolean(this.provider);\n }\n\n get label() {\n return this._label ?? (this.installed ? \"Installed\" : \"\");\n }\n\n async connect(onProgress?: ProgressReporter) {\n if (!this.provider) {\n throw Error(\"Provider not found\");\n }\n\n await this.provider.connectWallet(onProgress);\n const [address, publicKeyHex] = await Promise.all([this.provider.getAddress(), this.provider.getPublicKeyHex()]);\n\n this.account = { address, publicKeyHex };\n\n return this;\n }\n\n clone() {\n return new Wallet({\n id: this.id,\n origin: this.origin,\n name: this.name,\n icon: this.icon,\n iconBackground: this.iconBackground,\n docs: this.docs,\n networks: this.networks,\n provider: this.provider,\n });\n }\n}\n","export let createNanoEvents = () => ({\n emit(event, ...args) {\n for (\n let callbacks = this.events[event] || [],\n i = 0,\n length = callbacks.length;\n i < length;\n i++\n ) {\n callbacks[i](...args)\n }\n },\n events: {},\n on(event, cb) {\n ;(this.events[event] ||= []).push(cb)\n return () => {\n this.events[event] = this.events[event]?.filter(i => cb !== i)\n }\n }\n})\n","export const ERROR_CODES = {\n // ===== General/Common Errors =====\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\", // Fallback\n INVALID_PARAMS: \"INVALID_PARAMS\", // Validation error\n CONNECTION_FAILED: \"CONNECTION_FAILED\", // Connection error\n METHOD_NOT_IMPLEMENTED: \"METHOD_NOT_IMPLEMENTED\", // Unimplemented feature\n MAX_ITERATION_EXCEEDED: \"MAX_ITERATION_EXCEEDED\", // Exceeded allowed iterations\n\n // ===== Wallet Extension/Provider =====\n EXTENSION_NOT_FOUND: \"EXTENSION_NOT_FOUND\", // Extension missing\n EXTENSION_CONTEXT_INVALIDATED: \"EXTENSION_CONTEXT_INVALIDATED\", // Context invalidated\n CONNECTION_REJECTED: \"CONNECTION_REJECTED\", // User rejected\n CONNECTION_CANCELED: \"CONNECTION_CANCELED\", // User canceled\n CHAIN_ID_NOT_INITIALIZED: \"CHAIN_ID_NOT_INITIALIZED\", // Chain ID missing\n RPC_URL_NOT_INITIALIZED: \"RPC_URL_NOT_INITIALIZED\", // RPC URL missing\n FAILED_TO_ADD_CHAIN: \"FAILED_TO_ADD_CHAIN\", // Add chain failed\n FAILED_TO_GET_KEY: \"FAILED_TO_GET_KEY\", // Key fetch failed\n WALLET_INITIALIZATION_FAILED: \"WALLET_INITIALIZATION_FAILED\", // Wallet initialization failed\n WALLET_NOT_CONNECTED: \"WALLET_NOT_CONNECTED\", // Not connected\n INCOMPATIBLE_WALLET_VERSION: \"INCOMPATIBLE_WALLET_VERSION\", // Version mismatch\n WALLET_METHOD_NOT_SUPPORTED: \"WALLET_METHOD_NOT_SUPPORTED\", // Wallet does not implement a required method\n NETWORK_NOT_ENABLED_IN_WALLET: \"NETWORK_NOT_ENABLED_IN_WALLET\", // Network not enabled\n WALLET_CONFIG_REQUIRED: \"WALLET_CONFIG_REQUIRED\", // Wallet configuration required\n SHARED_SESSION_DISCONNECT_REFUSED: \"SHARED_SESSION_DISCONNECT_REFUSED\", // Disconnecting one chain would also disconnect another\n\n // ===== Bitcoin/PSBT/Address =====\n INVALID_PUBLIC_KEY: \"INVALID_PUBLIC_KEY\", // Invalid public key\n ADDRESS_GENERATION_FAILED: \"ADDRESS_GENERATION_FAILED\", // Address generation failed\n UNSUPPORTED_NETWORK: \"UNSUPPORTED_NETWORK\", // Network unsupported\n INVALID_ADDRESS_PREFIX: \"INVALID_ADDRESS_PREFIX\", // Address prefix invalid\n MISSING_PSBT_HEX: \"MISSING_PSBT_HEX\", // PSBT hex missing\n PSBT_HEX_REQUIRED: \"PSBT_HEX_REQUIRED\", // PSBT hex required\n PSBTS_HEXES_REQUIRED: \"PSBTS_HEXES_REQUIRED\", // Multiple PSBT hexes required\n SIGNATURE_EXTRACT_ERROR: \"SIGNATURE_EXTRACT_ERROR\", // Signature extraction failed\n GENERATION_ERROR: \"GENERATION_ERROR\", // General generation error\n ADDRESS_NOT_FOUND: \"ADDRESS_NOT_FOUND\", // Address not found\n PUBLIC_KEY_NOT_FOUND: \"PUBLIC_KEY_NOT_FOUND\", // Public key not found\n EMPTY_WITNESS_STACK: \"EMPTY_WITNESS_STACK\", // Witness stack is empty\n\n // ===== QR/Hardware Wallet =====\n QR_READ_ERROR: \"QR_READ_ERROR\", // QR read failed\n QR_SCAN_ERROR: \"QR_SCAN_ERROR\", // QR scan failed\n DEVICE_CEREMONY_INVALID: \"DEVICE_CEREMONY_INVALID\", // Device ceremony state unusable — restart from derivation\n DEVICE_LOCKED: \"DEVICE_LOCKED\", // Hardware device is PIN-locked\n DEVICE_WRONG_APP: \"DEVICE_WRONG_APP\", // Wrong app open on the hardware device\n\n // ===== Inscriptions/Network =====\n INSCRIPTIONS_UNSUPPORTED_NETWORK: \"INSCRIPTIONS_UNSUPPORTED_NETWORK\", // Inscriptions unsupported\n INSCRIPTION_FETCH_ERROR: \"INSCRIPTION_FETCH_ERROR\", // Inscription fetch failed\n};\n","import { ERROR_CODES } from \"./codes\";\n\ninterface ErrorParams {\n code: string;\n message: string;\n wallet?: string;\n version?: string;\n chainId?: string;\n}\n\nexport class WalletError extends Error {\n readonly code: string;\n readonly wallet?: string;\n readonly version?: string;\n readonly chainId?: string;\n\n constructor({ code, message, wallet, version, chainId }: ErrorParams, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.wallet = wallet;\n this.version = version;\n this.chainId = chainId;\n }\n}\n\n/**\n * Returns true when the underlying error message indicates the user rejected\n * a wallet prompt (sign, connect, approve). Wallet providers expose this in\n * varying phrasings — match the exact ones used by supported wallets, not\n * the bare word \"rejected\" (some validation errors include it too).\n */\nexport function isUserRejectionMessage(message: string | undefined): boolean {\n if (!message) return false;\n const lower = message.toLowerCase();\n return (\n lower.includes(\"user rejected\") ||\n lower.includes(\"user denied\") ||\n lower.includes(\"user cancelled\") ||\n lower.includes(\"user canceled\")\n );\n}\n\n/**\n * Returns true when a provider refused a chain-scoped disconnect because that\n * chain shares its wallet session with another chain. The refusal is a\n * designed answer, not a fault: nothing was disconnected.\n */\nexport function isSharedSessionRefusal(error: unknown): error is WalletError {\n return error instanceof WalletError && error.code === ERROR_CODES.SHARED_SESSION_DISCONNECT_REFUSED;\n}\n\nexport * from \"./codes\";\n","import { createNanoEvents } from \"nanoevents\";\n\nimport { Wallet } from \"@/core/Wallet\";\nimport type { DisconnectScope, IConnector, IProvider } from \"@/core/types\";\nimport { ERROR_CODES, WalletError, isSharedSessionRefusal } from \"@/error\";\n\ntype DisconnectableProvider = IProvider & { disconnect?: (scope: DisconnectScope) => Promise<void> };\n\nexport interface ConnectorEvents<P extends IProvider> {\n connecting: (message?: string, description?: string) => void;\n connect: (wallet: Wallet<P>) => void;\n disconnect: (wallet: Wallet<P>) => void;\n error: (error: Error) => void;\n}\n\nexport class WalletConnector<N extends string, P extends IProvider, C> implements IConnector<N, P, C> {\n private _connectedWallet: Wallet<P> | null = null;\n private _connectionGeneration = 0;\n private _ee = createNanoEvents<ConnectorEvents<P>>();\n\n constructor(\n public readonly id: N,\n public readonly name: string,\n public readonly icon: string,\n public readonly wallets: Wallet<P>[],\n public readonly config: C,\n ) {}\n\n get connectedWallet() {\n return this._connectedWallet;\n }\n\n async connect(wallet: string | Wallet<P>) {\n try {\n const selectedWallet = typeof wallet === \"string\" ? this.wallets.find((w) => w.id === wallet) : wallet;\n\n if (!selectedWallet) {\n throw new WalletError({\n code: ERROR_CODES.EXTENSION_NOT_FOUND,\n message: \"Wallet not found\",\n });\n }\n this._ee.emit(\"connecting\", `Connecting ${selectedWallet.name}`);\n\n const reportProgress = (message?: string, description?: string) =>\n this._ee.emit(\"connecting\", message, description);\n await selectedWallet.connect(reportProgress);\n this._connectedWallet = selectedWallet;\n this._connectionGeneration += 1;\n this._ee.emit(\"connect\", this._connectedWallet);\n\n return this.connectedWallet;\n } catch (e: any) {\n this._ee.emit(\"error\", e);\n return null;\n }\n }\n\n async disconnect(scope: DisconnectScope = \"chain\") {\n const wallet = this._connectedWallet;\n const generation = this._connectionGeneration;\n if (!wallet) return;\n\n const provider = wallet.provider as DisconnectableProvider | null;\n if (provider?.disconnect) {\n try {\n await provider.disconnect(scope);\n } catch (error) {\n if (scope === \"chain\" && isSharedSessionRefusal(error)) throw error;\n this._ee.emit(\"error\", error instanceof Error ? error : new Error(String(error)));\n if (scope === \"chain\") throw error;\n }\n }\n if (this._connectedWallet !== wallet || this._connectionGeneration !== generation) return;\n this._connectedWallet = null;\n this._ee.emit(\"disconnect\", wallet);\n }\n\n clone() {\n return new WalletConnector(this.id, this.name, this.icon, this.wallets, this.config);\n }\n\n on<K extends keyof ConnectorEvents<P>>(name: K, handler: ConnectorEvents<P>[K]) {\n return this._ee.on(name, handler);\n }\n}\n","import { ChainInfo, OfflineAminoSigner, OfflineDirectSigner } from \"@keplr-wallet/types\";\nimport { ComponentType } from \"react\";\n\nexport type Fees = {\n // fee for inclusion in the next block\n fastestFee: number;\n // fee for inclusion in a block in 30 mins\n halfHourFee: number;\n // fee for inclusion in a block in 1 hour\n hourFee: number;\n // economy fee: inclusion not guaranteed\n economyFee: number;\n // minimum fee: the minimum fee of the network\n minimumFee: number;\n};\n\n// UTXO is a structure defining attributes for a UTXO\nexport interface UTXO {\n // hash of transaction that holds the UTXO\n txid: string;\n // index of the output in the transaction\n vout: number;\n // amount of satoshis the UTXO holds\n value: number;\n // the script that the UTXO contains\n scriptPubKey: string;\n}\n\nexport interface InscriptionIdentifier {\n // hash of transaction that holds the ordinals/brc-2-/runes etc in the UTXO\n txid: string;\n // index of the output in the transaction\n vout: number;\n}\n// supported networks\nexport enum Network {\n MAINNET = \"mainnet\",\n TESTNET = \"testnet\",\n SIGNET = \"signet\",\n}\n\n// WalletInfo is a structure defining attributes for a wallet\nexport type WalletInfo = {\n publicKeyHex: string;\n address: string;\n};\n\nexport interface BTCConfig {\n coinName: string;\n coinSymbol: string;\n networkName: string;\n mempoolApiUrl: string;\n network: Network;\n}\n\nexport type BBNConfig = {\n chainId: string;\n rpc: string;\n chainData: ChainInfo;\n networkName: string;\n networkFullName: string;\n coinSymbol: string;\n};\n\nexport interface ETHConfig {\n chainId: number;\n chainName: string;\n rpcUrl: string;\n explorerUrl: string;\n nativeCurrency: {\n name: string;\n symbol: string;\n decimals: number;\n };\n}\n\n// Ethereum specific types\nexport interface ETHTransactionRequest {\n to: string;\n value?: string;\n data?: string;\n gasLimit?: bigint;\n maxFeePerGas?: bigint;\n maxPriorityFeePerGas?: bigint;\n nonce?: number;\n}\n\nexport interface ETHTypedData {\n domain: {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n salt?: string;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, any>;\n}\n\nexport interface NetworkInfo {\n name: string;\n chainId: string;\n}\n\nexport interface IETHProvider extends IProvider {\n /**\n * Signs a human-readable message using personal_sign\n * @param message - The message to sign\n * @returns A promise that resolves to the signature\n */\n signMessage(message: string): Promise<string>;\n\n /**\n * Signs structured data using eth_signTypedData_v4 (EIP-712)\n * @param typedData - The structured data to sign\n * @returns A promise that resolves to the signature\n */\n signTypedData(typedData: ETHTypedData): Promise<string>;\n\n /**\n * Sends a transaction to the blockchain\n * @param tx - The transaction request\n * @returns A promise that resolves to the transaction hash\n */\n sendTransaction(tx: ETHTransactionRequest): Promise<string>;\n\n /**\n * Estimates gas for a transaction\n * @param tx - The transaction request\n * @returns A promise that resolves to the estimated gas\n */\n estimateGas(tx: ETHTransactionRequest): Promise<bigint>;\n\n /**\n * Gets the current chain ID\n * @returns A promise that resolves to the chain ID\n */\n getChainId(): Promise<number>;\n\n /**\n * Switches to a different chain\n * @param chainId - The chain ID to switch to\n * @returns A promise that resolves when the switch is complete\n */\n switchChain(chainId: number): Promise<void>;\n\n /**\n * Gets the account balance\n * @returns A promise that resolves to the balance in wei\n */\n getBalance(): Promise<bigint>;\n\n /**\n * Gets the account nonce\n * @returns A promise that resolves to the nonce\n */\n getNonce(): Promise<number>;\n\n /**\n * Gets network information\n * @returns A promise that resolves to network info\n */\n getNetworkInfo(): Promise<NetworkInfo>;\n\n /**\n * Gets the wallet provider name\n * @returns The name of the wallet provider\n */\n getWalletProviderName(): string;\n\n /**\n * Gets the wallet provider icon\n * @returns The icon of the wallet provider\n */\n getWalletProviderIcon(): string;\n\n /**\n * Registers an event listener for the specified event\n * @param eventName - The name of the event to listen for\n * @param handler - The callback function to be executed when the event occurs\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n on(eventName: string, handler: Function): void;\n\n /**\n * Unregisters an event listener for the specified event\n * @param eventName - The name of the event to listen for\n * @param handler - The callback function to be executed when the event occurs\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n off(eventName: string, handler: Function): void;\n}\n\nexport type ProgressReporter = (message?: string, description?: string) => void;\n\nexport interface IProvider {\n connectWallet: (onProgress?: ProgressReporter) => Promise<void>;\n getAddress: () => Promise<string>;\n getPublicKeyHex: () => Promise<string>;\n isIdentityCurrent?: () => boolean;\n}\n\nexport interface IWallet<P extends IProvider = IProvider> {\n id: string;\n name: string;\n icon: string;\n // Solid brand-color fill shown behind `icon` in the wallet-select list, where\n // the icon is clipped to a rounded square rather than shown as a raw circle\n // (see WalletButton). Undefined falls back to no fill (transparent corners).\n iconBackground?: string;\n docs: string;\n installed: boolean;\n provider: P | null;\n account: Account | null;\n label: string;\n // Explicit hardware-wallet marker. Drives the \"available\" badge and the\n // connect-list ordering. Do NOT infer this from `label`: software wallets\n // (injectable, AppKit) carry labels too, so label truthiness is not a\n // hardware signal.\n hardware?: boolean;\n}\n\n/** Every chain the connector can build a wallet connector for. */\nexport type ChainId = \"BTC\" | \"BBN\" | \"ETH\";\n\n/**\n * `\"chain\"` asks the provider to disconnect only this connector's chain; the\n * provider refuses with `SHARED_SESSION_DISCONNECT_REFUSED` when that would\n * also disconnect another chain. `\"all\"` is an explicit disconnect-everything\n * request and is never refused. `\"local\"` drops this connector's wallet and\n * the provider's cached session without any remote call: for a wallet the app\n * rejected after connecting, or one the provider's backend already reports\n * disconnected. It is never refused.\n */\nexport type DisconnectScope = \"chain\" | \"all\" | \"local\";\n\nexport interface IChain<K extends string = string, P extends IProvider = IProvider, C = any> {\n id: K;\n name: string;\n icon: string;\n wallets: IWallet<P>[];\n config: C;\n}\n\nexport interface IConnector<K extends string = string, P extends IProvider = IProvider, C = any>\n extends IChain<K, P, C> {\n connect(wallet: string | IWallet<P>): Promise<IWallet<P> | null>;\n /**\n * Rejects only for `\"chain\"`: with `SHARED_SESSION_DISCONNECT_REFUSED` when\n * the provider refused, or with the provider's error when the remote\n * disconnect failed. Either way nothing was disconnected, so the wallet\n * stays connected and no `disconnect` event fires; only a genuine failure\n * is also reported on `error`. `\"all\"` and `\"local\"` always finish the\n * local teardown and report a provider failure on `error`.\n */\n disconnect(scope?: DisconnectScope): Promise<void>;\n on(event: string, cb: (wallet: IWallet<P>) => void): () => void;\n}\n\nexport interface Account {\n address: string;\n publicKeyHex: string;\n}\n\nexport interface WalletMetadata<P extends IProvider, C> {\n id: string;\n wallet?: string | ((context: any, config: C) => any);\n label?: string;\n // Marks the entry as a hardware wallet so the UI shows the \"available\" badge\n // and groups it after installed software wallets. Set explicitly per wallet.\n hardware?: boolean;\n name: string | ((wallet: any, config: C) => Promise<string>);\n icon: string | ((wallet: any, config: C) => Promise<string>);\n // See `IWallet.iconBackground`.\n iconBackground?: string;\n docs: string;\n networks: Network[];\n createProvider: (wallet: any, config: C) => P;\n}\n\nexport interface ChainMetadata<N extends string, P extends IProvider, C> {\n chain: N;\n name: string;\n icon: string;\n wallets: WalletMetadata<P, C>[];\n}\n\nexport interface ExternalWalletProps<P extends IProvider> {\n id: string;\n name: string;\n icon: string;\n provider: P;\n}\nexport interface WalletConnectorProps<N extends string, P extends IProvider, C> {\n persistent: boolean;\n metadata: ChainMetadata<N, P, C>;\n context: any;\n config: C;\n accountStorage: HashMap;\n disabledWallets?: string[];\n}\n\nexport interface WalletProps<P extends IProvider, C> {\n metadata: WalletMetadata<P, C>;\n context: any;\n config: C;\n}\n\nexport interface WidgetProps<P extends IProvider = IProvider> {\n id: string;\n connector: IConnector;\n createWallet: (props: ExternalWalletProps<P>) => IWallet<P>;\n onError?: (e: Error) => void;\n}\n\nexport type WidgetComponent<P extends IProvider = IProvider> = ComponentType<WidgetProps<P>>;\n\nexport interface ExternalConnector<P extends IProvider = IProvider> {\n id: string;\n widget: WidgetComponent<P>;\n}\n\nexport interface Contract {\n id: string;\n params: Record<string, string | number | string[] | number[]>;\n}\n\nexport interface Action {\n name: string;\n}\n\n/**\n * Options for signing a specific input in a PSBT.\n */\nexport interface SignInputOptions {\n /** Input index to sign */\n index: number;\n /** Address for signing (optional) */\n address?: string;\n /** Public key for signing (optional, hex string) */\n publicKey?: string;\n /** Sighash types (optional) */\n sighashTypes?: number[];\n /**\n * Whether the wallet should sign with the tweaked (key-path) signer.\n * Set `false` for Taproot script-path spends, where signing uses the\n * untweaked internal key. If omitted, the wallet's default behavior\n * applies.\n */\n useTweakedSigner?: boolean;\n /**\n * @deprecated Use `useTweakedSigner` instead. `disableTweakSigner: true`\n * is equivalent to `useTweakedSigner: false`; `useTweakedSigner` takes\n * precedence when both are set.\n *\n * `useTweakedSigner` is the canonical field used by UniSat and newer OKX\n * wallet versions. Migrating aligns our interface with the wallet-side\n * convention and avoids the historical divergence in OKX's\n * `disableTweakSigner` implementation.\n */\n disableTweakSigner?: boolean;\n}\n\nexport interface SignPsbtOptions {\n autoFinalized?: boolean;\n contracts?: Contract[];\n action?: Action;\n /**\n * Specific inputs to sign.\n * If not provided, wallet will attempt to sign all inputs it can.\n * Use this to restrict signing to specific inputs (e.g., only depositor's input in payout tx).\n */\n signInputs?: SignInputOptions[];\n /**\n * Human-readable label for the signing step (e.g. \"Transaction 3 of 12\").\n * Honored by wallets that render their own signing UI — Keystone shows it\n * above the QR code so the user can track progress through a batch. Wallets\n * that sign in their extension popup ignore it.\n */\n displayMessage?: string;\n}\n\n/** One committed device ceremony inside a `signPsbts` batch. Counts only — never payload. */\nexport interface SigningProgress {\n readonly completed: number;\n readonly total: number;\n}\n\nexport interface IBTCProvider extends IProvider {\n /**\n * Signs the given PSBT in hex format.\n * @param psbtHex - The hex string of the unsigned PSBT to sign.\n * @param options - Optional parameters for signing the PSBT.\n * @returns A promise that resolves to the hex string of the signed PSBT.\n */\n signPsbt(psbtHex: string, options?: SignPsbtOptions): Promise<string>;\n\n /**\n * Signs multiple PSBTs in hex format.\n * @param psbtsHexes - The hex strings of the unsigned PSBTs to sign.\n * @param options - Optional parameters for signing the PSBTs.\n * @returns A promise that resolves to an array of hex strings, each representing a signed PSBT.\n */\n signPsbts(psbtsHexes: string[], options?: SignPsbtOptions[]): Promise<string[]>;\n\n /**\n * Gets the network of the current account.\n * @returns A promise that resolves to the network of the current account.\n */\n getNetwork(): Promise<Network>;\n\n /**\n * Reads the wallet's live accounts WITHOUT prompting the user\n * (non-interactive). Implemented only by wallets where an empty result is a\n * reliable silent-lock signal: UniSat returns [] when the wallet is locked\n * while a stale cached `getAddress()` still reports the last-known address,\n * so it can be polled to detect a silent auto-lock that fires no event.\n * Unlike `connectWallet()` it never surfaces the unlock / connection popup.\n *\n * Intentionally omitted by OKX and OneKey: their `getAccounts()` returns the\n * cached / dApp-authorized address even when the keyring is locked, so an\n * empty-array read is not a lock signal there. Optional — callers MUST\n * feature-detect (`typeof provider.getAccounts === \"function\"`) and treat a\n * missing method as \"lock cannot be probed\", never as locked.\n * @returns A promise that resolves to the active account addresses.\n */\n getAccounts?(): Promise<string[]>;\n\n /**\n * Requests cancellation of the in-flight signing ceremony\n * (signPsbt/signPsbts/signMessage). A REQUEST, not a settle: the provider\n * aborts at its next device exchange boundary, and the sign promise rejects\n * with `CONNECTION_REJECTED` only then. No-op when nothing is in flight.\n *\n * Implemented only by hardware providers whose ceremonies block on a\n * physical device (currently the Ledger vault provider). Optional — callers\n * MUST feature-detect (`typeof provider.cancelSigning === \"function\"`) and\n * hide the cancel affordance when the method is missing.\n */\n cancelSigning?(): void;\n\n /**\n * Subscribes to per-PSBT progress inside `signPsbts`: fires after each\n * device ceremony commits, with `completed` = PSBT ceremonies committed\n * so far and `total` = the batch length. Never fires for `signPsbt`\n * or before the first ceremony. A ceremony that fails emits no tick, while\n * ticks for ceremonies that committed before a later rejection stand — the\n * promise settle is the terminal signal. Listeners run synchronously inside\n * the signing loop: a throw is swallowed, a returned promise is neither\n * awaited nor observed. Ticks carry no batch identity, so implementers MUST\n * reject an overlapping `signPsbts` rather than queue it. Returns the\n * unsubscribe. The subscription outlives a batch but not the session —\n * teardown (disconnect or dead-session cleanup) drops every listener, so\n * subscribe per sign call.\n *\n * Implemented only by hardware providers that run one device ceremony per\n * PSBT (currently the Ledger vault provider). Optional — callers MUST\n * feature-detect (`typeof provider.subscribeSigningProgress === \"function\"`)\n * and fall back to the batch settle when the method is missing.\n */\n subscribeSigningProgress?(listener: (progress: SigningProgress) => void): () => void;\n\n /**\n * Signs a message using either BIP322-Simple or ECDSA signing method.\n * @param message - The message to sign.\n * @param type - The signing method to use.\n * @returns A promise that resolves to the signed message.\n */\n signMessage(message: string, type: \"bip322-simple\" | \"ecdsa\"): Promise<string>;\n\n /**\n * Retrieves the inscriptions for the connected wallet.\n * @returns A promise that resolves to an array of inscriptions.\n */\n getInscriptions(): Promise<InscriptionIdentifier[]>;\n\n /**\n * Registers an event listener for the specified event.\n * At the moment, only the \"accountChanged\" event is supported.\n * @param eventName - The name of the event to listen for.\n * @param callBack - The callback function to be executed when the event occurs.\n */\n on(eventName: string, callBack: () => void): void;\n\n /**\n * Unregisters an event listener for the specified event.\n * @param eventName - The name of the event to listen for.\n * @param callBack - The callback function to be executed when the event occurs.\n */\n off(eventName: string, callBack: () => void): void;\n\n /**\n * Gets the name of the wallet provider.\n * @returns A promise that resolves to the name of the wallet provider.\n */\n getWalletProviderName(): Promise<string>;\n\n /**\n * Gets the icon of the wallet provider.\n * @returns A promise that resolves to the icon of the wallet provider.\n */\n getWalletProviderIcon(): Promise<string>;\n\n /**\n * Gets the version of the wallet provider.\n * @returns A promise that resolves to the version of the wallet provider.\n */\n getVersion?(): Promise<string>;\n\n /**\n * Derives a deterministic 32-byte value from the wallet's key material,\n * an application name, and an application-provided context string.\n *\n * Conforms to the `deriveContextHash` wallet API contract that the\n * ts-sdk conformance vectors pin\n * (`tbv/core/vault-secrets/__tests__/deriveContextHash.vectors.test.ts`).\n * Implementations\n * that do not support this method MUST throw a {@link WalletError}\n * with code {@link ERROR_CODES.WALLET_METHOD_NOT_SUPPORTED} so the\n * caller can branch deterministically on capability.\n *\n * The wallet itself enforces the contract's input/output validation\n * (`appName` charset and length, `context` even-length lowercase hex,\n * 64-char hex output). Adapters forward without re-validating.\n *\n * @param appName - Application identifier (1-64 bytes, `[a-z0-9\\-]`).\n * Displayed by the wallet in its approval dialog.\n * @param context - Application-specific context, hex-encoded\n * (even-length, lowercase, no `0x` prefix, non-empty,\n * ≤ 2048 hex chars / 1024 bytes).\n * @returns 64-char lowercase hex string (32 bytes).\n * @throws {@link WalletError} with code\n * {@link ERROR_CODES.WALLET_METHOD_NOT_SUPPORTED} when the wallet\n * does not implement the method.\n */\n deriveContextHash(appName: string, context: string): Promise<string>;\n}\n\nexport interface IBBNProvider extends IProvider {\n /**\n * Gets the name of the wallet provider.\n * @returns A promise that resolves to the name of the wallet provider.\n */\n getWalletProviderName(): Promise<string>;\n\n /**\n * Gets the icon of the wallet provider.\n * @returns A promise that resolves to the icon of the wallet provider.\n */\n getWalletProviderIcon(): Promise<string>;\n\n /**\n * Retrieves an offline signer that supports both Amino and Direct signing methods.\n * This signer is used for signing transactions offline before broadcasting them to the network.\n *\n * @returns {Promise<OfflineAminoSigner & OfflineDirectSigner>} A promise that resolves to a signer supporting both Amino and Direct signing\n * @throws {Error} If wallet connection is not established or signer cannot be retrieved\n */\n getOfflineSigner(): Promise<OfflineAminoSigner & OfflineDirectSigner>;\n\n /**\n * Retrieves an offline signer that supports either Amino or Direct signing methods.\n * This is required for compatibility with older wallets and hardware wallets (like Ledger) that do not support both signing methods.\n * This signer is used for signing transactions offline before broadcasting them to the network.\n *\n * @returns {Promise<OfflineAminoSigner & OfflineDirectSigner>} A promise that resolves to a signer supporting either Amino or Direct signing\n * @throws {Error} If wallet connection is not established or signer cannot be retrieved\n */\n getOfflineSignerAuto?(): Promise<OfflineAminoSigner | OfflineDirectSigner>;\n\n /**\n * Registers an event listener for the specified event.\n * At the moment, only the \"accountChanged\" event is supported.\n * @param eventName - The name of the event to listen for.\n * @param callBack - The callback function to be executed when the event occurs.\n */\n on(eventName: string, callBack: () => void): void;\n\n /**\n * Unregisters an event listener for the specified event.\n * @param eventName - The name of the event to listen for.\n * @param callBack - The callback function to be executed when the event occurs.\n */\n off(eventName: string, callBack: () => void): void;\n\n /**\n * Gets the version of the wallet provider.\n * @returns A promise that resolves to the version of the wallet provider.\n */\n getVersion?(): Promise<string>;\n}\n\nexport interface HashMap {\n get: (key: string) => string | undefined;\n set: (key: string, value: any) => void;\n has: (key: string) => boolean;\n delete: (key: string) => boolean;\n}\n","import { type WalletOptions, Wallet } from \"./Wallet\";\nimport { WalletConnector } from \"./WalletConnector\";\nimport { ExternalWalletProps, IProvider, Network, WalletConnectorProps, WalletProps } from \"./types\";\n\nconst defaultWalletGetter = (key: string) => (context: any) => context[key];\n\nexport const createWallet = async <P extends IProvider, C>({ metadata, context, config }: WalletProps<P, C>) => {\n const {\n id,\n wallet: walletGetter,\n name: nameGetter,\n icon: iconGetter,\n iconBackground,\n docs = \"\",\n networks = [],\n createProvider,\n label,\n hardware,\n } = metadata;\n\n const options: WalletOptions<P> = {\n id,\n name: \"\",\n icon: \"\",\n iconBackground,\n origin: null,\n provider: null,\n docs,\n networks,\n label,\n hardware,\n };\n\n if (walletGetter) {\n const getWallet = typeof walletGetter === \"string\" ? defaultWalletGetter(walletGetter) : walletGetter;\n\n options.origin = (await getWallet(context, config)) ?? null;\n options.provider = options.origin ? createProvider(options.origin, config) : null;\n } else {\n options.origin = null;\n options.provider = createProvider(null, config);\n }\n\n if (typeof nameGetter === \"string\") {\n options.name = nameGetter ?? \"\";\n } else {\n options.name = options.origin ? await nameGetter(options.origin, config) : \"\";\n }\n\n if (typeof iconGetter === \"string\") {\n options.icon = iconGetter ?? \"\";\n } else {\n options.icon = options.origin ? await iconGetter(options.origin, config) : \"\";\n }\n\n return new Wallet(options);\n};\n\nexport const createExternalWallet = <P extends IProvider>({ id, name, icon, provider }: ExternalWalletProps<P>) =>\n new Wallet({\n id,\n origin: null,\n name,\n icon,\n docs: \"\",\n networks: [Network.MAINNET, Network.SIGNET],\n provider,\n });\n\nexport const createWalletConnector = async <N extends string, P extends IProvider, C>({\n persistent,\n metadata,\n context,\n config,\n accountStorage,\n disabledWallets,\n}: WalletConnectorProps<N, P, C>): Promise<WalletConnector<N, P, C>> => {\n const wallets: Wallet<P>[] = [];\n const connectedWalletId = persistent ? accountStorage.get(metadata.chain) : undefined;\n\n for (const walletMetadata of metadata.wallets) {\n if (disabledWallets?.includes(walletMetadata.id)) {\n continue;\n }\n wallets.push(\n await createWallet({\n metadata: walletMetadata,\n context,\n config,\n }),\n );\n }\n const injectableWallet = wallets.find((w) => w.id === \"injectable\" && w.installed);\n const filteredWallets = wallets.filter(\n (w) => w.name.toLowerCase() !== injectableWallet?.name.toLowerCase() || w.id === \"injectable\",\n );\n const connector = new WalletConnector(metadata.chain, metadata.name, metadata.icon, filteredWallets, config);\n\n const shouldAutoReconnect =\n metadata.chain !== \"ETH\" &&\n connectedWalletId &&\n wallets.some((wallet) => wallet.id === connectedWalletId && wallet.installed);\n\n if (shouldAutoReconnect) {\n // Fire-and-forget: do NOT await the reconnect handshake. Awaiting it here\n // blocks `createWalletConnector`, and therefore `ChainProvider.init()`'s\n // `Promise.all` over every chain, on the BTC extension responding. A locked\n // or unresponsive wallet would otherwise hang init indefinitely and leave\n // the whole connection UI (BTC *and* ETH) stuck loading. The reconnect\n // result is delivered through the connector's `connect`/`error` events,\n // which `ChainProvider`, `BTCWalletProvider`, and `useWalletConnectors`\n // already subscribe to. `connector.connect` swallows its own errors, so the\n // extra catch is just defensive against an unexpected synchronous throw.\n void connector.connect(connectedWalletId).catch((error) => {\n console.error(\"Auto-reconnect failed:\", error instanceof Error ? error.message : \"Unknown error\");\n });\n }\n\n return connector;\n};\n","import type { HashMap, IProvider } from \"@/core/types\";\nimport type { WalletConnector } from \"@/core/WalletConnector\";\n\n/**\n * Decision (kept pure, and free of the SVG-importing wallet metadata, so it can\n * be unit-tested without React): which of the just-redetected connectors should\n * have their previously-stored session reconnected.\n *\n * A connector qualifies only when sessions are persisted, the trigger allows\n * reconnect (cold-start, not the interactive modal-open path — which must not\n * race a manual connect), its chain is **eligible** (it participated in a\n * late-injection redetection this session — see `eligibleChainIds` below),\n * storage still names a wallet for that chain, that wallet is now installed, and\n * the connector isn't already connected.\n *\n * `eligibleChainIds` is the key guard: only chains that actually late-injected\n * are eligible. ETH/AppKit never late-injects (it's always installed, so never\n * `stale`/`appeared`), so it's never eligible — which is what keeps this from\n * calling `ethConnector.connect()` and popping the AppKit modal on reload (core\n * excludes ETH from auto-reconnect for the same reason).\n */\nexport function selectRedetectReconnectTargets({\n connectors,\n storage,\n allowReconnect,\n persistent,\n eligibleChainIds,\n}: {\n connectors: WalletConnector<string, IProvider, any>[];\n storage: Pick<HashMap, \"get\">;\n allowReconnect: boolean;\n persistent: boolean;\n eligibleChainIds: Set<string>;\n}): { connector: WalletConnector<string, IProvider, any>; walletId: string }[] {\n if (!allowReconnect || !persistent) return [];\n\n const targets: { connector: WalletConnector<string, IProvider, any>; walletId: string }[] = [];\n for (const connector of connectors) {\n if (!eligibleChainIds.has(connector.id)) continue;\n if (connector.connectedWallet) continue;\n const storedWalletId = storage.get(connector.id);\n if (!storedWalletId) continue;\n if (!connector.wallets.some((w) => w.id === storedWalletId && w.installed)) continue;\n targets.push({ connector, walletId: storedWalletId });\n }\n return targets;\n}\n","import type { Dispatch, SetStateAction } from \"react\";\nimport { useEffect, useRef } from \"react\";\n\nimport { WALLET_MODAL_OPEN_EVENT } from \"@/constants/walletEvents\";\nimport { createWalletConnector } from \"@/core\";\nimport type { HashMap, IProvider } from \"@/core/types\";\nimport type { WalletConnector } from \"@/core/WalletConnector\";\nimport type { ChainConfigArr, ChainMetadataMap, Connectors } from \"@/context/Chain.context\";\n\nimport { selectRedetectReconnectTargets } from \"./redetectReconnect\";\n\n/** UniSat dispatches this on `window` once its provider is ready. */\nconst UNISAT_READY_EVENT = \"unisat#initialized\";\n\n/**\n * Fallback delay for the cold-start re-detection when no wallet emits a ready\n * event. Long enough to cover UniSat's phishing-detection await, short enough\n * that a genuinely-uninstalled wallet isn't shown as \"checking\" for long.\n */\nconst FALLBACK_MS = 3000;\n\ninterface UseWalletRedetectionParams {\n /** Current connector map from `ChainProvider` state. */\n connectors: Connectors;\n /** `ChainProvider`'s connector-state setter. */\n setConnectors: Dispatch<SetStateAction<Connectors>>;\n /** Per-chain config array — same one passed to `createWalletConnector`. */\n config: Readonly<ChainConfigArr>;\n /** Wallet-detection context — typically `window`. */\n context: any;\n /** Account storage used for connector construction. */\n storage: HashMap;\n /** Wallet ids to exclude from connector construction. */\n disabledWallets?: string[];\n /**\n * Whether sessions are persisted (same flag passed to `createWalletConnector`).\n * When true, a cold-start re-detection that re-installs a previously-stored\n * wallet auto-reconnects it (see the reconnect block below).\n */\n persistent: boolean;\n /** Chain metadata for the entry point in use — see `ChainMetadataMap`. */\n metadata: ChainMetadataMap;\n}\n\n/**\n * Late-injection re-detection.\n *\n * Browser wallet extensions inject their `window` provider asynchronously\n * (e.g. UniSat's content script awaits phishing-detection before defining\n * `window.unisat`), so the one-shot detection in `ChainProvider`'s `init()`\n * can run before the extension is ready and leave a genuinely-installed\n * wallet stuck at `installed: false` — the wallet modal then shows it as a\n * download link instead of a connect button.\n *\n * Once the connectors are built, this re-detects on whichever of these fires:\n * UniSat's `unisat#initialized` event, a short fallback timeout (covers\n * wallets that emit no ready event), or every time the wallet modal opens\n * (`WALLET_MODAL_OPEN_EVENT`) — the last one covers an extension that injects\n * later than the fallback, so it still flips to a connect button by the time\n * the user looks at the list. Same event-or-timeout approach wagmi and\n * MetaMask's `detect-provider` use for this race.\n *\n * Re-detection is idempotent and safe to run repeatedly: only not-yet-connected\n * chains with an undetected wallet are rebuilt (it bails immediately when there\n * are none), and the merge re-checks connection state, so a live connection is\n * never dropped. A single in-flight guard prevents overlapping passes (e.g. the\n * event and the timeout firing close together).\n *\n * The connector *rebuild* always passes `persistent: false` so it does no\n * auto-reconnect itself. Reconnect of a previously-stored session is then\n * done explicitly, and only for the **cold-start** triggers (`unisat#initialized`\n * and the fallback timeout) where the modal is closed and there is no manual\n * connect to race. The interactive `WALLET_MODAL_OPEN_EVENT` trigger stays\n * detect-only (`allowReconnect: false`) — the user is actively choosing a wallet\n * there, so auto-reconnecting could double-prompt. Without this, a session that\n * lost the cold-start detection race (extension injected after `init()`) would\n * stay disconnected even though storage still names the wallet — leaving e.g.\n * ETH reconnected while BTC/UniSat shows as \"Connect\".\n */\nexport function useWalletRedetection({\n connectors,\n setConnectors,\n config,\n context,\n storage,\n disabledWallets,\n persistent,\n metadata,\n}: UseWalletRedetectionParams): void {\n // Mirror the latest connectors into a ref so the effect reads current\n // state without depending on it (which would re-run it).\n const connectorsRef = useRef(connectors);\n connectorsRef.current = connectors;\n\n // True once `init()` has populated the connectors.\n const connectorsBuilt = Object.values(connectors).some(Boolean);\n\n useEffect(() => {\n // Arm only after `init()` has populated connectors — otherwise a fast\n // event/timeout could consume a re-detect against an empty set.\n if (!connectorsBuilt) return;\n\n let inFlight = false; // prevent overlapping passes (event vs. timeout vs. modal-open)\n let cancelled = false; // effect cleaned up\n // Chains with a stored-session reconnect already in flight, so the two\n // cold-start triggers (ready event + fallback timer) firing before it\n // settles don't fire duplicate `connect()`s. Persists across redetect calls\n // within this effect instance.\n const reconnecting = new Set<string>();\n // Chains that participated in late-injection redetection (their wallet\n // `appeared` after the one-shot init detection) and still need their stored\n // session restored. Only these are eligible for redetect reconnect — so\n // ETH/AppKit (never late-injects) and normally-detected wallets (init\n // auto-reconnect handles them) are excluded. Persists across passes so a\n // modal-open detect-only pass that swaps a wallet in is still restored by a\n // later cold-start pass.\n const pendingRestore = new Set<string>();\n\n // `allowReconnect` is true only for the non-interactive cold-start triggers\n // (see listeners below); the modal-open trigger passes false.\n const redetect = async (allowReconnect: boolean) => {\n if (inFlight || cancelled) return;\n inFlight = true;\n try {\n await runRedetection(allowReconnect);\n } finally {\n inFlight = false;\n }\n };\n\n const runRedetection = async (allowReconnect: boolean) => {\n // 1. Re-detect connectors whose wallet injected after the one-shot\n // detection in init() (e.g. UniSat) and swap the now-installed ones in.\n const stale = (\n Object.values(connectorsRef.current).filter(Boolean) as WalletConnector<string, IProvider, any>[]\n ).filter(\n (c) =>\n Boolean(metadata[c.id as keyof ChainMetadataMap]) &&\n !c.connectedWallet &&\n c.wallets.some((w) => w.id !== \"injectable\" && !w.installed),\n );\n\n let swapIn: WalletConnector<string, IProvider, any>[] = [];\n if (stale.length > 0) {\n const rebuilt = await Promise.all(\n stale.map((c) =>\n createWalletConnector<string, IProvider, any>({\n // `persistent: false` — this rebuild only re-detects providers; the\n // stored-session reconnect is done explicitly in step 2 so it can\n // also cover connectors an earlier detect-only pass already swapped in.\n persistent: false,\n metadata: metadata[c.id as keyof ChainMetadataMap]!,\n context,\n config: config.find((cc) => cc.chain === c.id)?.config,\n accountStorage: storage,\n disabledWallets,\n }).catch(() => null),\n ),\n );\n if (cancelled) return;\n\n // Keep only chains where a wallet that was NOT installed before is\n // installed now (robust to the injectable-wallet de-dup reshaping the\n // list, vs. a plain installed-count comparison).\n const appeared = rebuilt.filter((c): c is WalletConnector<string, IProvider, any> => {\n if (!c) return false;\n const before = connectorsRef.current[c.id as keyof Connectors];\n if (!before || before.connectedWallet) return false;\n const wasInstalled = new Set(before.wallets.filter((w) => w.installed).map((w) => w.id));\n return c.wallets.some((w) => w.installed && !wasInstalled.has(w.id));\n });\n\n // These chains late-injected — mark them eligible for stored-session\n // restore (carried across passes, so a detect-only modal-open pass is\n // still restored by a later cold-start pass).\n for (const c of appeared) pendingRestore.add(c.id);\n\n // Swap in the appeared connectors whose currently-in-state counterpart\n // hasn't connected in the meantime. Computed synchronously (not inside\n // the updater) so it doesn't depend on side effects in the deferred /\n // possibly double-invoked state updater.\n const current = connectorsRef.current;\n swapIn = appeared.filter((c) => !current[c.id as keyof Connectors]?.connectedWallet);\n if (swapIn.length > 0) {\n setConnectors((prev) => {\n const next: Record<string, WalletConnector<string, IProvider, any>> = {};\n for (const c of swapIn) {\n // Re-check at commit time for the tiny window since `swapIn` was computed.\n if (prev[c.id as keyof Connectors]?.connectedWallet) continue;\n next[c.id] = c;\n }\n return Object.keys(next).length > 0 ? ({ ...prev, ...next } as Connectors) : prev;\n });\n }\n }\n\n // 2. Restore persisted sessions (cold-start triggers only — the modal-open\n // trigger stays detect-only so it can't race a manual connect). Only\n // chains in `pendingRestore` (late-injected this session) are eligible,\n // so ETH/AppKit and normally-detected wallets are never reconnected\n // here. The in-state instance is taken from swapIn (this pass) or\n // current, so a session swapped in by an earlier detect-only pass is\n // still restored.\n if (!allowReconnect || !persistent || pendingRestore.size === 0) return;\n const inState: Record<string, WalletConnector<string, IProvider, any>> = {};\n for (const c of Object.values(connectorsRef.current)) {\n if (c) inState[c.id] = c as WalletConnector<string, IProvider, any>;\n }\n for (const c of swapIn) inState[c.id] = c;\n\n const reconnectTargets = selectRedetectReconnectTargets({\n connectors: Object.values(inState),\n storage,\n allowReconnect,\n persistent,\n eligibleChainIds: pendingRestore,\n });\n for (const { connector, walletId } of reconnectTargets) {\n if (reconnecting.has(connector.id)) continue;\n reconnecting.add(connector.id);\n // Fire-and-forget: `connect` swallows its own errors (returns null on\n // failure); a locked/unresponsive wallet must not block re-detection.\n // The connect event flows through the normal ChainProvider bump /\n // BTCWalletProvider / selectWallet wiring (which repopulates selectedWallets).\n void connector\n .connect(walletId)\n .then((wallet) => {\n reconnecting.delete(connector.id);\n // Restored — stop treating this chain as pending so later cold-start\n // passes don't reconnect it again. On failure `connect` resolves\n // null, so it stays pending and a later trigger retries.\n if (wallet) pendingRestore.delete(connector.id);\n })\n .catch(() => reconnecting.delete(connector.id));\n }\n };\n\n const redetectColdStart = () => void redetect(true);\n const redetectInteractive = () => void redetect(false);\n\n const timer = setTimeout(redetectColdStart, FALLBACK_MS);\n const hasWindow = typeof window !== \"undefined\";\n if (hasWindow) {\n // Cold-start race: re-detect (and restore the stored session) once the\n // extension signals it is ready.\n window.addEventListener(UNISAT_READY_EVENT, redetectColdStart, { once: true });\n // Catch-all for an injection slower than FALLBACK_MS: re-detect whenever\n // the user opens the modal. Repeatable (not `once`); the in-flight guard\n // and the no-stale-wallets early-return keep it cheap when nothing changed.\n // Detect-only (no reconnect) so it can't race the user's manual connect.\n window.addEventListener(WALLET_MODAL_OPEN_EVENT, redetectInteractive);\n }\n\n return () => {\n cancelled = true;\n clearTimeout(timer);\n if (hasWindow) {\n window.removeEventListener(UNISAT_READY_EVENT, redetectColdStart);\n window.removeEventListener(WALLET_MODAL_OPEN_EVENT, redetectInteractive);\n }\n };\n }, [connectorsBuilt, config, context, storage, disabledWallets, setConnectors, persistent, metadata]);\n}\n","\"use client\";\n\nimport { type Dispatch, type SetStateAction, useEffect, useState } from \"react\";\n\nexport function usePersistState<S>(key: string, storage: Storage, initialState: S): [S, Dispatch<SetStateAction<S>>] {\n function getDefaultState() {\n const defaultValue = typeof initialState === \"function\" ? (initialState as () => S)() : initialState;\n\n if (typeof storage === \"undefined\") {\n return defaultValue;\n }\n\n const persistValue = storage.getItem(key);\n const defaultState = persistValue ? (JSON.parse(persistValue) as S) : null;\n\n return (defaultState ?? defaultValue) as S;\n }\n\n const [state, setState] = useState<S>(getDefaultState);\n\n useEffect(\n function updateLocalStorage() {\n storage.setItem(key, JSON.stringify(state ?? \"\"));\n },\n [key, storage, state],\n );\n\n return [state, setState];\n}\n","import { createContext, PropsWithChildren, useContext, useMemo } from \"react\";\n\nimport { usePersistState } from \"@/hooks/usePersistState\";\n\ninterface InscriptionContext {\n lockInscriptions: boolean;\n toggleLockInscriptions?: (value: boolean) => void;\n}\n\nconst Context = createContext<InscriptionContext>({ lockInscriptions: true });\n\nexport function InscriptionProvider({ children, context }: PropsWithChildren<{ context: any }>) {\n const [lockInscriptions, toggleLockInscriptions] = usePersistState(\n \"bwc-inscription-modal-lock\",\n context.localStorage,\n true,\n );\n\n const inscriptionContext = useMemo(\n () => ({\n lockInscriptions,\n toggleLockInscriptions,\n }),\n [lockInscriptions, toggleLockInscriptions],\n );\n\n return <Context.Provider value={inscriptionContext}>{children}</Context.Provider>;\n}\n\nexport const useInscriptionProvider = () => useContext(Context);\n","import { DISCONNECT_EVENT, NETWORK_CHANGE_EVENT } from \"@/constants/walletEvents\";\nimport type { Connectors } from \"@/context/Chain.context\";\nimport type { Account, ChainId, IBTCProvider, IETHProvider, IProvider, IWallet } from \"@/core/types\";\n\nexport const WALLET_CONFIRMATION_RECEIPT_KEY = \"__babylon-wallet-confirmation-v1__\";\n\nconst RECEIPT_VERSION = 2;\n\nexport interface ConfirmationConnection {\n chain: ChainId;\n wallet: IWallet;\n account: Account;\n}\n\ninterface ConfirmationReceiptEntry {\n chain: ChainId;\n walletId: string;\n address: string;\n publicKeyHex: string;\n network: string;\n}\n\ninterface ConfirmationReceipt {\n version: typeof RECEIPT_VERSION;\n entries: ConfirmationReceiptEntry[];\n}\n\nconst IDENTITY_CHANGE_EVENTS: Record<ChainId, readonly string[]> = {\n BTC: [\"accountsChanged\", NETWORK_CHANGE_EVENT, DISCONNECT_EVENT],\n BBN: [\"accountChanged\"],\n ETH: [\"accountsChanged\", \"chainChanged\"],\n};\n\ntype IdentityEventProvider = IProvider & {\n on?: (event: string, handler: (...args: unknown[]) => void) => void;\n off?: (event: string, handler: (...args: unknown[]) => void) => void;\n};\n\nfunction connectorFor(connectors: Connectors, chain: ChainId) {\n return connectors[chain];\n}\n\n/**\n * The network a chain's connector is pointed at. A receipt approved on signet\n * must not restore a session against mainnet, so this participates in the\n * match alongside the account identity.\n */\nfunction networkIdentity(\n connectors: Connectors,\n chain: ChainId,\n networks?: Partial<Record<ChainId, string | number>>,\n): string {\n const config = connectorFor(connectors, chain)?.config as\n | { chainId?: string | number; network?: string | number }\n | undefined;\n const value = networks?.[chain] ?? (chain === \"BTC\" ? config?.network : config?.chainId);\n\n return value === undefined ? \"\" : String(value);\n}\n\nexport function sameIdentity(left: string, right: string): boolean {\n return left.toLowerCase() === right.toLowerCase();\n}\n\nfunction isReceiptEntry(value: unknown): value is ConfirmationReceiptEntry {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\n const entry = value as Partial<ConfirmationReceiptEntry>;\n\n return (\n typeof entry.chain === \"string\" &&\n typeof entry.walletId === \"string\" &&\n typeof entry.address === \"string\" &&\n typeof entry.publicKeyHex === \"string\" &&\n typeof entry.network === \"string\"\n );\n}\n\nfunction parseConfirmationReceipt(serialized: string | undefined): ConfirmationReceipt | undefined {\n if (!serialized) return;\n\n try {\n const receipt = JSON.parse(serialized) as Partial<ConfirmationReceipt>;\n if (\n receipt?.version !== RECEIPT_VERSION ||\n !Array.isArray(receipt.entries) ||\n !receipt.entries.every(isReceiptEntry)\n ) {\n return;\n }\n\n return receipt as ConfirmationReceipt;\n } catch {\n return;\n }\n}\n\n/**\n * Serializes what the user approved: the wallet, account and network of every\n * chain connected at the moment they confirmed.\n *\n * Deliberately records the connected set rather than the required set. A host\n * that varies its requirements per route would otherwise mint a receipt on one\n * route that cannot satisfy the next, and sign the user out on navigation.\n */\nexport function createConfirmationReceipt(\n connections: readonly ConfirmationConnection[],\n connectors: Connectors,\n networks?: Partial<Record<ChainId, string | number>>,\n): string {\n const entries = connections\n .filter((connection) => connection.account && connectorFor(connectors, connection.chain))\n .map<ConfirmationReceiptEntry>((connection) => ({\n chain: connection.chain,\n walletId: connection.wallet.id,\n address: connection.account.address,\n publicKeyHex: connection.account.publicKeyHex,\n network: networkIdentity(connectors, connection.chain, networks),\n }))\n .sort((left, right) => left.chain.localeCompare(right.chain));\n\n return JSON.stringify({ version: RECEIPT_VERSION, entries } satisfies ConfirmationReceipt);\n}\n\n/**\n * True when the stored approval covers every currently-required chain and each\n * one still matches the live connection.\n *\n * Coverage, not equality: a receipt may name chains that are not required right\n * now, which is what lets a host narrow and widen its requirements — per route,\n * say — without invalidating an approval the user already gave. A required\n * chain the receipt does not name is never covered, so consent is still never\n * inherited by a chain, account, wallet or network the user did not approve.\n */\nexport function isValidConfirmationReceipt(\n serialized: string | undefined,\n requiredChainIds: readonly string[],\n connectors: Connectors,\n): boolean {\n const entries = parseConfirmationReceipt(serialized)?.entries;\n if (!entries) return false;\n\n // An empty requirement set is satisfied by any receipt, but never by none:\n // the caller still has to have an approval on file.\n return requiredChainIds.every((chainId) => {\n const chain = chainId as ChainId;\n const wallet = connectorFor(connectors, chain)?.connectedWallet;\n const account = wallet?.account;\n const entry = entries.find((candidate) => candidate.chain === chain);\n\n return Boolean(\n wallet &&\n account &&\n entry &&\n entry.walletId === wallet.id &&\n sameIdentity(entry.address, account.address) &&\n sameIdentity(entry.publicKeyHex, account.publicKeyHex) &&\n entry.network === networkIdentity(connectors, chain),\n );\n });\n}\n\nexport function isConfirmationReceiptCovered(\n serialized: string | undefined,\n requiredChainIds: readonly string[],\n connectors: Connectors,\n): boolean {\n const entries = parseConfirmationReceipt(serialized)?.entries;\n if (!entries) return false;\n\n return requiredChainIds.every((chainId) => {\n const chain = chainId as ChainId;\n const wallet = connectorFor(connectors, chain)?.connectedWallet;\n const entry = entries.find((candidate) => candidate.chain === chain);\n\n return Boolean(\n wallet && entry && entry.walletId === wallet.id && entry.network === networkIdentity(connectors, chain),\n );\n });\n}\n\n/** Checks the current provider values instead of the connector's cached account. */\nexport async function isLiveConfirmationReceiptValid(\n serialized: string | undefined,\n requiredChainIds: readonly string[],\n connectors: Connectors,\n): Promise<boolean> {\n const entries = parseConfirmationReceipt(serialized)?.entries;\n if (!entries) return false;\n\n const matches = await Promise.all(\n requiredChainIds.map(async (chainId) => {\n const chain = chainId as ChainId;\n const connector = connectorFor(connectors, chain);\n const wallet = connector?.connectedWallet;\n const provider = wallet?.provider;\n const entry = entries.find((candidate) => candidate.chain === chain);\n if (!wallet || !provider || !entry || entry.walletId !== wallet.id) return false;\n\n try {\n if (provider.isIdentityCurrent?.() === false) return false;\n const [address, publicKeyHex, network] = await Promise.all([\n provider.getAddress(),\n provider.getPublicKeyHex(),\n chain === \"ETH\"\n ? (provider as IETHProvider).getChainId()\n : chain === \"BTC\"\n ? (provider as IBTCProvider).getNetwork()\n : networkIdentity(connectors, chain),\n ]);\n if (provider.isIdentityCurrent?.() === false) return false;\n\n return (\n sameIdentity(entry.address, address) &&\n sameIdentity(entry.publicKeyHex, publicKeyHex) &&\n entry.network === String(network)\n );\n } catch {\n return false;\n }\n }),\n );\n\n return matches.every(Boolean);\n}\n\nexport function subscribeToConfirmationIdentityChanges(\n serialized: string,\n requiredChainIds: readonly string[],\n connectors: Connectors,\n onChange: (chain: ChainId) => void,\n): () => void {\n const entries = parseConfirmationReceipt(serialized)?.entries;\n if (!entries) return () => {};\n\n const subscriptions: Array<{\n event: string;\n handler: (...args: unknown[]) => void;\n provider: IdentityEventProvider;\n }> = [];\n\n requiredChainIds.forEach((chainId) => {\n const chain = chainId as ChainId;\n const provider = connectors[chain]?.connectedWallet?.provider as IdentityEventProvider | null | undefined;\n if (!provider?.on) return;\n\n IDENTITY_CHANGE_EVENTS[chain]?.forEach((event) => {\n const handler = (...args: unknown[]) => {\n const accounts = args[0];\n const approved = entries.find((entry) => entry.chain === chain);\n if (\n chain === \"ETH\" &&\n event === \"accountsChanged\" &&\n Array.isArray(accounts) &&\n accounts.length === 1 &&\n typeof accounts[0] === \"string\" &&\n approved &&\n sameIdentity(approved.address, accounts[0])\n ) {\n return;\n }\n\n onChange(chain);\n };\n\n try {\n provider.on?.(event, handler);\n subscriptions.push({ event, handler, provider });\n } catch {\n // Some wallet adapters reject event names they do not support.\n }\n });\n });\n\n return () => {\n subscriptions.forEach(({ event, handler, provider }) => {\n try {\n provider.off?.(event, handler);\n } catch {\n // The provider can disconnect before the listener is removed.\n }\n });\n };\n}\n\n/** Chains the stored approval names, whether or not they are required now. */\nexport function confirmedChains(serialized: string | undefined): ChainId[] {\n return parseConfirmationReceipt(serialized)?.entries.map((entry) => entry.chain) ?? [];\n}\n","import { type PropsWithChildren, createContext, useEffect, useInsertionEffect, useMemo, useRef, useState } from \"react\";\n\nimport { WALLET_MODAL_OPEN_EVENT } from \"@/constants/walletEvents\";\nimport { WALLET_CONFIRMATION_RECEIPT_KEY } from \"@/core/confirmationReceipt\";\nimport type { HashMap, IChain, IWallet } from \"@/core/types\";\n\nexport type Screen<T extends string = string> = {\n type: T;\n params?: Record<string, any>;\n};\n\nexport type Screens =\n | Screen<\"LOADER\">\n | Screen<\"CHAINS\">\n | Screen<\"WALLETS\">\n | Screen<\"ERROR\">;\n\nexport interface State {\n confirmed: boolean;\n /** The wallet identity that the user approved for this live session. */\n confirmationReceipt?: string;\n visible: boolean;\n screen: Screens;\n selectedWallets: Record<string, IWallet | undefined>;\n /** Every chain the dialog displays. */\n chains: Record<string, IChain>;\n /**\n * The subset of `chains` a host requires before the session counts as\n * connected. Chains outside this set are offered but never block confirm.\n */\n requiredChainIds: string[];\n}\n\nexport interface Actions {\n open?: () => void;\n close?: () => void;\n displayLoader?: (message?: string, description?: string) => void;\n displayChains?: () => void;\n displayWallets?: (chain: string) => void;\n displayError?: (params: {\n icon?: JSX.Element;\n title: string;\n description: string;\n cancelButton?: string;\n submitButton?: string;\n onCancel?: () => void;\n onSubmit?: () => void;\n }) => void;\n selectWallet?: (chain: string, wallet: IWallet) => void;\n removeWallet?: (chain: string) => void;\n confirm?: (receipt: string) => void;\n /** Withdraws the confirmation without disconnecting anything. */\n unconfirm?: (keepReceipt?: boolean) => void;\n reset?: () => void;\n}\n\nconst defaultState: State = {\n confirmed: false,\n visible: false,\n screen: { type: \"CHAINS\" },\n chains: {},\n selectedWallets: {},\n requiredChainIds: [],\n};\n\nexport const StateContext = createContext<State & Actions>(defaultState);\n\ninterface StateProviderProps {\n chains: IChain[];\n requiredChainIds: readonly string[];\n storage?: HashMap;\n}\n\n// Filters selected wallets to only include those that belong to currently valid chains.\n// This ensures wallet state stays in sync when the available chains configuration changes.\nfunction filterWalletsByValidChains(\n selectedWallets: Record<string, IWallet | undefined>,\n validChainIds: Set<string>\n): Record<string, IWallet | undefined> {\n return Object.keys(selectedWallets).reduce((acc, key) => {\n if (validChainIds.has(key)) {\n acc[key] = selectedWallets[key];\n }\n return acc;\n }, {} as Record<string, IWallet | undefined>);\n}\n\nexport function StateProvider({ children, chains, requiredChainIds, storage }: PropsWithChildren<StateProviderProps>) {\n const [state, setState] = useState<State>(() => ({\n ...defaultState,\n chains: chains.reduce((acc, chain) => ({ ...acc, [chain.id]: chain }), {}),\n requiredChainIds: [...requiredChainIds],\n }));\n const requirementsExpanded = requiredChainIds.some((chainId) => !state.requiredChainIds.includes(chainId));\n const renderedState = useMemo(\n () => ({\n ...state,\n confirmed: requirementsExpanded ? false : state.confirmed,\n requiredChainIds: [...requiredChainIds],\n }),\n [requiredChainIds, requirementsExpanded, state],\n );\n const requiredChainIdsRef = useRef(requiredChainIds);\n useInsertionEffect(() => {\n requiredChainIdsRef.current = requiredChainIds;\n }, [requiredChainIds]);\n // Expose new requirements as unconfirmed during render. This prevents a\n // child from observing one approved commit before live validation starts.\n useEffect(() => {\n setState((state) => {\n const newChains = chains.reduce((acc, chain) => ({ ...acc, [chain.id]: chain }), {});\n const validChainIds = new Set(chains.map((chain) => chain.id));\n const filteredWallets = filterWalletsByValidChains(state.selectedWallets, validChainIds);\n const requirementsExpanded = requiredChainIds.some((chainId) => !state.requiredChainIds.includes(chainId));\n\n return {\n ...state,\n confirmed: requirementsExpanded ? false : state.confirmed,\n chains: newChains,\n selectedWallets: filteredWallets,\n requiredChainIds: [...requiredChainIds],\n };\n });\n }, [chains, requiredChainIds]);\n\n const actions: Actions = useMemo(\n () => ({\n open: () => {\n // Let late-injection re-detection (useWalletRedetection) re-check for\n // wallets that injected after the initial detection before the user\n // sees the wallet list — otherwise a slow extension shows as a\n // download link until the next reload.\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(WALLET_MODAL_OPEN_EVENT));\n }\n setState((state) => ({ ...state, visible: true }));\n },\n\n close: () => {\n setState((state) => ({ ...state, visible: false }));\n },\n\n reset: () => {\n storage?.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n setState(({ chains, requiredChainIds }) => ({ ...defaultState, chains, requiredChainIds }));\n },\n\n displayLoader: (message = \"\", description = \"\") => {\n setState((state) => ({ ...state, screen: { type: \"LOADER\", params: { message, description } } }));\n },\n\n displayChains: () => {\n setState((state) => ({ ...state, screen: { type: \"CHAINS\" } }));\n },\n\n displayWallets: (chain: string) => {\n setState((state) => ({ ...state, screen: { type: \"WALLETS\", params: { chain } } }));\n },\n\n displayError: (params) => {\n setState((state) => ({ ...state, screen: { type: \"ERROR\", params } }));\n },\n\n selectWallet: (chain: string, wallet: IWallet) => {\n setState((state) => ({\n ...state,\n selectedWallets: { ...state.selectedWallets, [chain]: wallet },\n }));\n },\n\n removeWallet: (chain: string) => {\n const required = requiredChainIdsRef.current.includes(chain);\n if (required) {\n storage?.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n }\n setState((state) => ({\n ...state,\n // Losing an optional chain must not tear down a confirmed session.\n // Losing a required one does invalidate the confirmation, so\n // reconnecting cannot silently restore it.\n confirmed: required ? false : state.confirmed,\n confirmationReceipt: required ? undefined : state.confirmationReceipt,\n selectedWallets: { ...state.selectedWallets, [chain]: undefined },\n }));\n },\n\n confirm: (confirmationReceipt: string) => {\n setState((state) => ({ ...state, confirmed: true, confirmationReceipt }));\n },\n\n unconfirm: (keepReceipt = false) => {\n setState((state) => ({\n ...state,\n confirmed: false,\n confirmationReceipt: keepReceipt ? state.confirmationReceipt : undefined,\n }));\n },\n }),\n [storage],\n );\n\n const context = useMemo(\n () => ({\n ...renderedState,\n ...actions,\n }),\n [renderedState, actions],\n );\n\n return <StateContext.Provider value={context}>{children}</StateContext.Provider>;\n}\n","import { createContext, PropsWithChildren, useCallback, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport { createWalletConnector } from \"@/core\";\nimport { WalletConnector } from \"@/core/WalletConnector\";\nimport type {\n BBNConfig,\n BTCConfig,\n ChainId,\n ChainMetadata,\n ETHConfig,\n ExternalConnector,\n HashMap,\n IBBNProvider,\n IBTCProvider,\n IETHProvider,\n IProvider,\n} from \"@/core/types\";\nimport { useWalletRedetection } from \"@/hooks/useWalletRedetection\";\n\nimport { InscriptionProvider } from \"./Inscriptions.context\";\nimport { StateProvider } from \"./State.context\";\n\nexport interface ChainConfig<K extends string = string, P extends IProvider = IProvider, C = any> {\n chain: K;\n name?: string;\n icon?: string;\n config: C;\n connectors?: ExternalConnector<P>[];\n}\n\nexport type ChainConfigArr = (\n | ChainConfig<\"BTC\", IBTCProvider, BTCConfig>\n | ChainConfig<\"BBN\", IBBNProvider, BBNConfig>\n | ChainConfig<\"ETH\", IETHProvider, ETHConfig>\n)[];\n\n/**\n * Chain metadata is injected rather than imported, so an entry point can hand\n * over only the chains it supports. The `./eth` entry passes `{ ETH }` alone,\n * which keeps every Bitcoin wallet adapter out of its module graph.\n */\nexport interface ChainMetadataMap {\n BTC?: ChainMetadata<\"BTC\", IBTCProvider, BTCConfig>;\n BBN?: ChainMetadata<\"BBN\", IBBNProvider, BBNConfig>;\n ETH?: ChainMetadata<\"ETH\", IETHProvider, ETHConfig>;\n}\n\ninterface ProviderProps {\n persistent: boolean;\n storage: HashMap;\n context: any;\n config: Readonly<ChainConfigArr>;\n onError?: (e: Error) => void;\n disabledWallets?: string[];\n /** Defaults to every configured chain, which is the pre-optional-chains behaviour. */\n requiredChains?: readonly ChainId[];\n metadata: ChainMetadataMap;\n}\n\nexport interface Connectors {\n BTC: WalletConnector<\"BTC\", IBTCProvider, BTCConfig> | null;\n BBN: WalletConnector<\"BBN\", IBBNProvider, BBNConfig> | null;\n ETH: WalletConnector<\"ETH\", IETHProvider, ETHConfig> | null;\n}\n\nconst defaultState: Connectors = {\n BTC: null,\n BBN: null,\n ETH: null,\n};\n\nexport const Context = createContext<Connectors>(defaultState);\n\nexport function ChainProvider({\n persistent,\n storage,\n children,\n context,\n config,\n onError,\n disabledWallets,\n requiredChains,\n metadata,\n}: PropsWithChildren<ProviderProps>) {\n const [connectors, setConnectors] = useState(defaultState);\n\n const init = useCallback(async () => {\n const filteredConfig = config.filter((c) => metadata[c.chain]);\n\n const connectorPromises = filteredConfig.map(async ({ chain, config }) => {\n const chainMetadata = metadata[chain];\n if (!chainMetadata) return null;\n\n try {\n const connector = await createWalletConnector<string, IProvider, any>({\n persistent,\n metadata: chainMetadata,\n context,\n config,\n accountStorage: storage,\n disabledWallets,\n });\n return connector;\n } catch (error) {\n console.error(\"[ChainProvider] failed to create connector for chain:\", chain, error instanceof Error ? error.message : \"Unknown error\");\n throw error;\n }\n });\n\n const connectorArr = await Promise.all(connectorPromises);\n\n return connectorArr.reduce<Connectors>(\n (acc, connector) => (connector ? { ...acc, [connector.id]: connector } : acc),\n { ...defaultState },\n );\n }, [persistent, config, context, storage, disabledWallets, metadata]);\n\n useEffect(() => {\n init()\n .then((connectors) => {\n setConnectors(connectors);\n })\n .catch((error) => {\n console.error(\"[ChainProvider] init failed with error:\", error instanceof Error ? error.message : \"Unknown error\");\n onError?.(error);\n });\n }, [setConnectors, init, onError]);\n\n // Re-detect wallets whose extension injected after the one-shot detection\n // in `init()` above (e.g. UniSat's late `window.unisat` injection).\n useWalletRedetection({ connectors, setConnectors, config, context, storage, disabledWallets, persistent, metadata });\n\n // Auto-reconnect (and any other connect/disconnect) mutates `connectedWallet`\n // on the existing connector instance without changing the `connectors` object\n // identity, so consumers that read `connector.connectedWallet` reactively —\n // e.g. the auto-confirm-on-reload effect in `useWalletConnectors` — would not\n // re-evaluate. Because the BTC reconnect is now fire-and-forget (see\n // `createWalletConnector`), that mutation lands *after* the connectors are in\n // state. Bump a fresh `connectors` object on each connect/disconnect so those\n // consumers re-render and observe the new connection state.\n useEffect(() => {\n const active = Object.values(connectors).filter(Boolean) as WalletConnector<string, IProvider, any>[];\n if (active.length === 0) return;\n\n const bump = () => setConnectors((prev) => ({ ...prev }));\n const unsubscribe = active.flatMap((connector) => [connector.on(\"connect\", bump), connector.on(\"disconnect\", bump)]);\n\n return () => unsubscribe.forEach((fn) => fn());\n }, [connectors]);\n\n // Every chain that built a connector is displayed. `requiredChains` used to\n // filter this list, which meant a host could not offer a wallet without also\n // demanding it; it now gates only the confirm button and session restore.\n const supportedChains = useMemo(\n () => Object.values(connectors).filter((connector): connector is NonNullable<typeof connector> => Boolean(connector)),\n [connectors],\n );\n const requiredChainIds = useMemo(\n () =>\n requiredChains === undefined\n ? config.filter((entry) => metadata[entry.chain]).map((entry) => entry.chain)\n : [...requiredChains],\n [config, metadata, requiredChains],\n );\n\n return (\n <InscriptionProvider context={context}>\n <StateProvider chains={supportedChains} requiredChainIds={requiredChainIds} storage={storage}>\n <Context.Provider value={connectors}>{children}</Context.Provider>\n </StateProvider>\n </InscriptionProvider>\n );\n}\n\nexport const useChainProviders = () => {\n return useContext(Context);\n};\n","import { createContext, PropsWithChildren, useContext, useMemo } from \"react\";\n\nimport type { Account, ChainId, IWallet } from \"@/core/types\";\n\nexport interface WalletLifecycleConnection {\n chain: ChainId;\n wallet: IWallet;\n account: Account;\n}\n\nexport interface TermsOfServiceParams {\n /**\n * Address of the connected account for the first required chain. Read\n * `connections` instead whenever the chain the address belongs to matters —\n * this is a Bitcoin account only for hosts that require Bitcoin first.\n */\n address: string;\n /** Public key of that same account. Read `connections` instead when the chain matters. */\n public_key: string;\n chain: ChainId;\n connections: WalletLifecycleConnection[];\n}\n\nexport interface LifeCycleHooksProps {\n verifyBTCAddress?: (address: string) => Promise<boolean>;\n /**\n * Fires once when the user confirms the wallet dialog, not when an\n * individual wallet connects, and is skipped when an already-confirmed\n * session is confirmed again.\n */\n acceptTermsOfService?: (params: TermsOfServiceParams) => Promise<void>;\n onConfirm?: (connections: WalletLifecycleConnection[]) => void | Promise<void>;\n}\n\nconst Context = createContext<LifeCycleHooksProps>({});\n\nexport function LifeCycleHooksProvider({ children, value }: PropsWithChildren<{ value?: LifeCycleHooksProps }>) {\n const context = useMemo(() => {\n return value ?? {};\n }, [value]);\n\n return <Context.Provider value={context}>{children}</Context.Provider>;\n}\n\nexport const useLifeCycleHooks = () => useContext(Context);\n","import type { HashMap } from \"./types\";\n\nconst CONNECTED_ACCOUNTS_KEY = \"baby-connected-wallet-accounts\";\n\n/**\n * Scopes a chain key with its network identifier so that persisted\n * wallet connections from one network are not auto-restored on another.\n * e.g. \"BTC\" with network \"mainnet\" → \"BTC:mainnet\"\n */\nfunction scopeKey(key: string, networkMap?: Record<string, string>): string {\n const network = networkMap?.[key];\n return network ? `${key}:${network}` : key;\n}\n\n/**\n * Safely reads and parses the connected accounts map from localStorage.\n * On parse failure (corrupted data), clears the corrupted entry and returns an empty map.\n */\nfunction readAccountsMap(): Record<string, unknown> {\n const raw = localStorage.getItem(CONNECTED_ACCOUNTS_KEY);\n if (!raw) return {};\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n localStorage.removeItem(CONNECTED_ACCOUNTS_KEY);\n return {};\n }\n return parsed as Record<string, unknown>;\n } catch (e) {\n console.error(\"[account-storage] Failed to parse accounts map, clearing corrupted entry:\", e);\n localStorage.removeItem(CONNECTED_ACCOUNTS_KEY);\n return {};\n }\n}\n\n/**\n * Safely writes the accounts map to localStorage.\n * On write failure (quota exceeded, serialization error), clears the entry to avoid stale state.\n */\nfunction writeAccountsMap(map: Record<string, unknown>): void {\n try {\n localStorage.setItem(CONNECTED_ACCOUNTS_KEY, JSON.stringify(map));\n } catch (e) {\n console.error(\"[account-storage] Failed to write accounts map, clearing entry:\", e);\n localStorage.removeItem(CONNECTED_ACCOUNTS_KEY);\n }\n}\n\n/**\n * Factory method instantiates an instance of persistent key value storage with predefined ttl value\n * @param ttl - time to live in ms\n * @param networkMap - maps chain IDs to their network identifiers (e.g. { BTC: \"mainnet\", ETH: \"1\" })\n * so entries are scoped per-network and won't cross-restore on network changes\n * @returns - key value storage\n */\nexport const createAccountStorage = (ttl: number, networkMap?: Record<string, string>): HashMap => {\n function getTimestamps(map: Record<string, unknown>): Record<string, number> {\n const timestamps = map._timestamps;\n if (timestamps && typeof timestamps === \"object\" && !Array.isArray(timestamps)) {\n return timestamps as Record<string, number>;\n }\n return {};\n }\n\n function isExpired(map: Record<string, unknown>, scoped: string): boolean {\n const timestamps = getTimestamps(map);\n const ts = timestamps[scoped];\n if (typeof ts !== \"number\" || !Number.isFinite(ts)) return true;\n\n const now = Date.now();\n // Clamp to a sane window. Without these, an XSS-tier write of\n // ts=Number.MAX_SAFE_INTEGER (or any far-future value) makes\n // `now - ts` negative and the entry never expires; a backwards\n // clock jump similarly extends entries past the intended TTL.\n if (ts < 0) return true;\n if (ts > now + ttl) return true;\n return now - ts > ttl;\n }\n\n return {\n get: (key: string) => {\n const map = readAccountsMap();\n const scoped = scopeKey(key, networkMap);\n\n if (isExpired(map, scoped)) {\n return undefined;\n }\n\n return map[scoped] as string | undefined;\n },\n has: (key: string) => {\n const map = readAccountsMap();\n const scoped = scopeKey(key, networkMap);\n\n if (isExpired(map, scoped)) {\n return false;\n }\n\n return Boolean(map[scoped]);\n },\n set: (key: string, value: string) => {\n const map = readAccountsMap();\n const scoped = scopeKey(key, networkMap);\n const timestamps = getTimestamps(map);\n\n map[scoped] = value;\n map._timestamps = { ...timestamps, [scoped]: Date.now() };\n writeAccountsMap(map);\n },\n delete: (key: string) => {\n const map = readAccountsMap();\n const scoped = scopeKey(key, networkMap);\n const timestamps = getTimestamps(map);\n\n const deleted = Reflect.deleteProperty(map, scoped);\n delete timestamps[scoped];\n map._timestamps = timestamps;\n writeAccountsMap(map);\n return deleted;\n },\n };\n};\n","// Fill shown behind wallet marks that ship as a single-colour glyph with no\n// background of their own (OKX, Ledger, Keystone, OneKey). Without it the mark\n// disappears against a same-coloured surface — black glyphs vanish in dark mode.\n// Wallets whose logo already carries its own colour (MetaMask, UniSat, Keplr)\n// leave `iconBackground` undefined and render bare.\nexport const MONOCHROME_MARK_BACKGROUND = \"#000000\";\n\nexport const ONEKEY_BRAND_GREEN = \"#1FE121\";\n","export default \"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20width='225px'%20height='224px'%20viewBox='0%200%20225%20224'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3ctitle%3eokx%3c/title%3e%3cg%20id='Page-1'%20stroke='none'%20strokeWidth='1'%20fill='none'%20fill-rule='evenodd'%3e%3cg%20id='okx'%20transform='translate(0.401000,%200.006000)'%20fill='%23FFFFFF'%20fill-rule='nonzero'%3e%3cpath%20d='M144.382,74.667%20L79.673,74.667%20C76.924,74.667%2074.695,76.895%2074.695,79.644%20L74.695,144.354%20C74.695,147.103%2076.924,149.332%2079.673,149.332%20L144.382,149.332%20C147.131,149.332%20149.36,147.103%20149.36,144.354%20L149.36,79.644%20C149.36,76.895%20147.131,74.667%20144.382,74.667%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M69.687,0%20L4.978,0%20C2.229,0%200,2.228%200,4.978%20L0,69.687%20C0,72.436%202.229,74.665%204.978,74.665%20L69.687,74.665%20C72.437,74.665%2074.665,72.436%2074.665,69.687%20L74.665,4.978%20C74.665,2.228%2072.437,0%2069.687,0%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M219.017,0%20L154.307,0%20C151.558,0%20149.329,2.228%20149.329,4.978%20L149.329,69.687%20C149.329,72.436%20151.558,74.665%20154.307,74.665%20L219.017,74.665%20C221.766,74.665%20223.994,72.436%20223.994,69.687%20L223.994,4.978%20C223.994,2.228%20221.766,0%20219.017,0%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M69.687,149.328%20L4.978,149.328%20C2.229,149.328%200,151.556%200,154.305%20L0,219.015%20C0,221.764%202.229,223.993%204.978,223.993%20L69.687,223.993%20C72.437,223.993%2074.665,221.764%2074.665,219.015%20L74.665,154.305%20C74.665,151.556%2072.437,149.328%2069.687,149.328%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M219.017,149.328%20L154.307,149.328%20C151.558,149.328%20149.329,151.556%20149.329,154.305%20L149.329,219.015%20C149.329,221.764%20151.558,223.993%20154.307,223.993%20L219.017,223.993%20C221.766,223.993%20223.994,221.764%20223.994,219.015%20L223.994,154.305%20C223.994,151.556%20221.766,149.328%20219.017,149.328%20Z'%20id='Path'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/svg%3e\"","/**\n * Event dispatched to open the AppKit modal\n *\n * Both ETH and BTC AppKit connectors dispatch this event to trigger\n * the unified AppKit modal opening.\n */\nexport const APPKIT_OPEN_EVENT = \"babylon:open-appkit\";\n\n/**\n * Connector ids live here rather than beside their wallet metadata so a\n * consumer can match on one without importing the other chain's metadata\n * module — the `./eth` entry reads `APPKIT_ETH_CONNECTOR_ID` and must not pull\n * `btc/appkit` in with it.\n */\nexport const APPKIT_ETH_CONNECTOR_ID = \"appkit-eth-connector\";\nexport const APPKIT_BTC_CONNECTOR_ID = \"appkit-btc-connector\";\n","import type { createAppKit } from \"@reown/appkit/react\";\nimport type { Chain } from \"viem\";\nimport type { Config } from \"wagmi\";\n\nimport { ERROR_CODES, WalletError } from \"@/error\";\n\nimport type { SharedBtcAppKitConfig } from \"../btc/appkit/sharedConfig\";\n\nexport type AppKitModal = ReturnType<typeof createAppKit>;\n\ninterface AppKitMetadata {\n name: string;\n description: string;\n url: string;\n icons: readonly string[];\n}\n\nexport interface AppKitCapabilities {\n readonly projectId: string;\n readonly metadataFingerprint: string;\n readonly ethFingerprint?: string;\n readonly btcNetwork?: \"mainnet\" | \"signet\";\n}\n\nexport interface AppKitState extends AppKitCapabilities {\n readonly modal: AppKitModal;\n readonly wagmiConfig?: Config;\n readonly btcConfig?: SharedBtcAppKitConfig;\n}\n\nconst BIGINT_FINGERPRINT_TYPE = \"bigint\";\nconst FUNCTION_FINGERPRINT_TYPE = \"function\";\nconst CONFIG_FINGERPRINT_SERIALIZATION_ERROR = \"AppKit configuration cannot be serialized.\";\nconst INITIAL_CONFIG_FUNCTION_ID = 1;\nconst configFunctionIds = new WeakMap<object, number>();\nlet nextConfigFunctionId = INITIAL_CONFIG_FUNCTION_ID;\n\nfunction getConfigFunctionId(value: object): number {\n const existingId = configFunctionIds.get(value);\n if (existingId) return existingId;\n\n const id = nextConfigFunctionId++;\n configFunctionIds.set(value, id);\n return id;\n}\n\nfunction createConfigFingerprint(value: object): string {\n const fingerprint = JSON.stringify(value, (_key, nestedValue) => {\n if (typeof nestedValue === BIGINT_FINGERPRINT_TYPE) {\n return { type: BIGINT_FINGERPRINT_TYPE, value: nestedValue.toString() };\n }\n\n if (typeof nestedValue === FUNCTION_FINGERPRINT_TYPE) {\n return { type: FUNCTION_FINGERPRINT_TYPE, value: getConfigFunctionId(nestedValue) };\n }\n\n if (nestedValue && typeof nestedValue === \"object\" && !Array.isArray(nestedValue)) {\n return Object.fromEntries(\n Object.entries(nestedValue).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)),\n );\n }\n\n return nestedValue;\n });\n\n if (fingerprint === undefined) {\n throw new TypeError(CONFIG_FINGERPRINT_SERIALIZATION_ERROR);\n }\n\n return fingerprint;\n}\n\nexport function createAppKitCapabilities({\n projectId,\n metadata,\n ethChain,\n btcNetwork,\n}: {\n projectId: string;\n metadata: AppKitMetadata;\n ethChain?: Chain;\n btcNetwork?: \"mainnet\" | \"signet\";\n}): AppKitCapabilities {\n return Object.freeze({\n projectId,\n metadataFingerprint: createConfigFingerprint(metadata),\n ethFingerprint: ethChain ? createConfigFingerprint(ethChain) : undefined,\n btcNetwork,\n });\n}\n\n/**\n * AppKit allows one modal instance per page. The instance is held here rather\n * than in either initializer so the unified (ETH+BTC) and Ethereum-only setups\n * observe the same singleton without the Ethereum-only one having to import\n * the Bitcoin adapter through its sibling.\n */\nlet appKitState: AppKitState | null = null;\nlet manualAppKitModal: AppKitModal | null = null;\nconst manualAppKitCapabilities = new Set<\"Ethereum\" | \"Bitcoin\">();\n\nexport function failInitialization(message: string, chainId?: string): never {\n throw new WalletError({ code: ERROR_CODES.WALLET_INITIALIZATION_FAILED, message, chainId });\n}\n\nexport function getAppKitState(): AppKitState | null {\n return appKitState;\n}\n\nexport function getAppKitModal(): AppKitModal | null {\n return appKitState?.modal ?? manualAppKitModal;\n}\n\nexport function registerManualAppKitConfig(capability: \"Ethereum\" | \"Bitcoin\", modal?: AppKitModal): void {\n if (appKitState) {\n failInitialization(\n `Cannot set a manual ${capability} AppKit configuration after AppKit initialization. Use the canonical AppKit state.`,\n );\n }\n\n manualAppKitCapabilities.add(capability);\n if (modal) manualAppKitModal = modal;\n}\n\n/** @internal */\nexport function __resetManualAppKitConfigForTests(capability: \"Ethereum\" | \"Bitcoin\"): void {\n manualAppKitCapabilities.delete(capability);\n if (capability === \"Bitcoin\") manualAppKitModal = null;\n}\n\nexport function validateAppKitInitialization(projectId?: string): projectId is string {\n if (!projectId) {\n if (appKitState) {\n failInitialization(\n \"AppKit is already initialized. A project ID is required to validate the requested configuration.\",\n );\n }\n\n return false;\n }\n\n if (manualAppKitCapabilities.size > 0) {\n failInitialization(\n `Cannot initialize AppKit after a manual ${[...manualAppKitCapabilities].join(\" and \")} configuration was set. Use only one initialization method.`,\n );\n }\n\n return true;\n}\n\nexport function setAppKitState(state: AppKitState): AppKitState {\n if (appKitState) {\n failInitialization(\"AppKit is already initialized. Reuse the shared AppKit state instead of replacing it.\");\n }\n\n if (manualAppKitCapabilities.size > 0) {\n failInitialization(\"Cannot publish AppKit state after a manual shared configuration was set.\");\n }\n\n appKitState = Object.freeze({\n ...state,\n btcConfig: state.btcConfig ? Object.freeze({ ...state.btcConfig }) : undefined,\n });\n return appKitState;\n}\n\nexport function assertAppKitCapabilities(existing: AppKitCapabilities, requested: AppKitCapabilities): void {\n if (existing.projectId !== requested.projectId) {\n failInitialization(\n \"AppKit was already initialized with a different project ID. A page can use only one AppKit configuration.\",\n );\n }\n\n if (existing.metadataFingerprint !== requested.metadataFingerprint) {\n failInitialization(\n \"AppKit was already initialized with different metadata. A page can use only one AppKit configuration.\",\n );\n }\n\n if (requested.ethFingerprint) {\n if (!existing.ethFingerprint) {\n failInitialization(\n \"AppKit was already initialized without Ethereum support. A page that needs Ethereum must initialize AppKit with Ethereum first.\",\n \"ETH\",\n );\n }\n\n if (existing.ethFingerprint !== requested.ethFingerprint) {\n failInitialization(\"AppKit was already initialized with a different Ethereum chain configuration.\", \"ETH\");\n }\n }\n\n if (requested.btcNetwork) {\n if (!existing.btcNetwork) {\n failInitialization(\n \"AppKit was already initialized without Bitcoin support. A page that needs Bitcoin must initialize AppKit with Bitcoin first.\",\n \"BTC\",\n );\n }\n\n if (existing.btcNetwork !== requested.btcNetwork) {\n failInitialization(\"AppKit was already initialized with a different Bitcoin network.\", \"BTC\");\n }\n }\n}\n","import type { Config } from \"wagmi\";\n\nimport {\n failInitialization,\n getAppKitModal,\n getAppKitState,\n registerManualAppKitConfig,\n} from \"@/core/wallets/appkit/state\";\n\nconst ETHEREUM_CAPABILITY = \"Ethereum\";\nconst SHARED_WAGMI_REPLACEMENT_WARNING =\n \"Shared wagmi config is being replaced. This might indicate multiple initializations.\";\n\n/**\n * Shared wagmi config singleton\n *\n * This allows the AppKitProvider (class-based) to access the wagmi config\n * that's provided by the application-level WagmiProvider.\n *\n * Use `initializeAppKitModal` for canonical initialization. Use\n * `setSharedWagmiConfig` only when another owner initializes AppKit. Do not\n * combine these modes on the same page. `AppKitProvider` reads either mode\n * through `getSharedWagmiConfig`.\n */\n\nlet sharedWagmiConfig: Config | null = null;\n\nexport function setSharedWagmiConfig(config: Config): void {\n registerManualAppKitConfig(ETHEREUM_CAPABILITY);\n\n if (sharedWagmiConfig && sharedWagmiConfig !== config) {\n console.warn(SHARED_WAGMI_REPLACEMENT_WARNING);\n }\n sharedWagmiConfig = config;\n}\n\nexport function getSharedWagmiConfig(): Config {\n const initializedState = getAppKitState();\n if (initializedState) {\n if (!initializedState.wagmiConfig) {\n failInitialization(\n \"AppKit was initialized without Ethereum support. Initialize it with Ethereum support.\",\n \"ETH\",\n );\n }\n\n return initializedState.wagmiConfig;\n }\n\n if (!sharedWagmiConfig) {\n throw new Error(\n \"Shared wagmi config not initialized. \" +\n \"Initialize AppKit with Ethereum support, or use setSharedWagmiConfig() as an exclusive manual alternative.\",\n );\n }\n return sharedWagmiConfig;\n}\n\nexport function hasSharedWagmiConfig(): boolean {\n const initializedState = getAppKitState();\n return initializedState ? initializedState.wagmiConfig !== undefined : sharedWagmiConfig !== null;\n}\n\nexport function ethDisconnectWouldDropBitcoin(): boolean {\n const modal = getAppKitModal();\n const providerType = modal?.getProviderType(\"eip155\");\n return providerType === \"WALLET_CONNECT\" && modal?.getAccount(\"bip122\")?.isConnected === true;\n}\n","import { parseEther } from \"viem\";\nimport {\n connect,\n getAccount,\n getTransactionCount,\n disconnect as wagmiDisconnect,\n estimateGas as wagmiEstimateGas,\n getBalance as wagmiGetBalance,\n sendTransaction as wagmiSendTransaction,\n signMessage as wagmiSignMessage,\n signTypedData as wagmiSignTypedData,\n switchChain as wagmiSwitchChain,\n watchAccount,\n watchChainId,\n} from \"wagmi/actions\";\nimport { walletConnect } from \"wagmi/connectors\";\n\nimport type {\n DisconnectScope,\n ETHConfig,\n ETHTransactionRequest,\n ETHTypedData,\n IETHProvider,\n NetworkInfo,\n} from \"@/core/types\";\nimport { APPKIT_OPEN_EVENT } from \"@/core/wallets/appkit/constants\";\n// Read the modal from the shared singleton rather than from `appKitModal`,\n// which pulls the Bitcoin adapter in with it.\nimport { getAppKitModal } from \"@/core/wallets/appkit/state\";\nimport { ERROR_CODES, WalletError } from \"@/error\";\n\nimport { ethDisconnectWouldDropBitcoin, getSharedWagmiConfig, hasSharedWagmiConfig } from \"./sharedConfig\";\n\n// Grace period after modal close before rejecting as cancelled, to allow\n// async handoffs (WalletConnect deep-link, mobile wallet return) to publish\n// the connected account via watchAccount before we treat the close as a cancel.\nconst MODAL_CLOSE_CANCEL_GRACE_MS = 1500;\nconst WALLET_NOT_CONNECTED_ERROR_MESSAGE = \"Wallet not connected\";\n\n// Generic Ethereum logo, used only when the active wagmi connector does not\n// expose its own name/icon (e.g. some WalletConnect sessions).\nconst ETH_FALLBACK_PROVIDER_NAME = \"Ethereum Wallet\";\nconst ETH_FALLBACK_PROVIDER_ICON =\n \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=\";\n\n/**\n * AppKitProvider - ETH wallet provider using AppKit/Wagmi\n *\n * This provider integrates with Reown's AppKit to provide:\n * - Connection to 600+ ETH wallets (MetaMask, Rainbow, WalletConnect, etc.)\n * - Message signing (personal_sign)\n * - Typed data signing (eth_signTypedData_v4)\n * - Transaction sending and gas estimation\n * - Network switching and information\n *\n * IMPORTANT: Requires shared wagmi config to be set via initializeAppKitModal()\n * before this provider is instantiated. This ensures single wagmi instance.\n */\nexport class AppKitProvider implements IETHProvider {\n private config: ETHConfig;\n private address?: string;\n private chainId?: number;\n private eventHandlers: Map<string, Set<(...args: any[]) => void>> = new Map();\n private unwatchFunctions: (() => void)[] = [];\n\n constructor(config: ETHConfig) {\n this.config = config;\n this.ensureEventWatchers();\n }\n\n /**\n * Attach the wagmi watchers exactly once, and only when the shared config\n * exists. The provider is now constructed unconditionally (it no longer\n * waits on an injected `window.ethereum`), so construction must not throw\n * when AppKit init has not run or has fallen back — that would take down the\n * BTC connector alongside the ETH one. `connectWallet` re-checks and still\n * surfaces the actionable \"AppKit ETH not initialized\" error, and calling\n * this again there picks the watchers up if init landed late.\n */\n private ensureEventWatchers(): void {\n if (this.unwatchFunctions.length > 0) return;\n if (!hasSharedWagmiConfig()) return;\n this.setupEventWatchers();\n }\n\n /**\n * Get the shared wagmi config (throws if not set)\n * This ensures we never create multiple wagmi instances\n */\n private getWagmiConfig() {\n if (!hasSharedWagmiConfig()) {\n throw new Error(\n \"AppKit ETH not initialized. Ensure AppKit modal is initialized at application startup \" +\n \"by calling initializeAppKitModal() with eth config in your app's entry point.\",\n );\n }\n return getSharedWagmiConfig();\n }\n\n private setupEventWatchers(): void {\n const config = this.getWagmiConfig();\n\n // Check for existing connection on initialization (for auto-reconnection)\n const initialAccount = getAccount(config);\n if (initialAccount.address && initialAccount.status === \"connected\") {\n this.address = initialAccount.address;\n this.chainId = initialAccount.chainId;\n // Emit connect event after a short delay to ensure provider is fully initialized\n setTimeout(() => {\n this.emit(\"accountsChanged\", [initialAccount.address!]);\n }, 100);\n }\n\n // Watch for account changes\n const unwatchAccount = watchAccount(config, {\n onChange: (account) => {\n const previousAddress = this.address;\n this.address = account.address;\n this.chainId = account.chainId;\n\n if (previousAddress !== account.address) {\n this.emit(\"accountsChanged\", account.address ? [account.address] : []);\n }\n },\n });\n\n const unwatchChain = watchChainId(config, {\n onChange: (chainId) => {\n const previousChainId = this.chainId;\n this.chainId = chainId;\n\n if (previousChainId !== chainId) {\n this.emit(\"chainChanged\", `0x${chainId.toString(16)}`);\n }\n },\n });\n\n this.unwatchFunctions.push(unwatchAccount, unwatchChain);\n }\n\n private emit(eventName: string, data?: any): void {\n const handlers = this.eventHandlers.get(eventName);\n if (handlers) {\n handlers.forEach((handler) => handler(data));\n }\n }\n\n async connectWallet(): Promise<void> {\n try {\n const config = this.getWagmiConfig();\n // Init may have completed after this provider was constructed.\n this.ensureEventWatchers();\n\n // First check if already connected (from previous session)\n const currentAccount = getAccount(config);\n if (currentAccount.address) {\n this.address = currentAccount.address;\n this.chainId = currentAccount.chainId;\n return;\n }\n\n // Open AppKit modal for manual connection\n if (typeof window !== \"undefined\") {\n const waitForConnection = new Promise<void>((resolve, reject) => {\n let modalHasOpened = false;\n let pendingCancellation: ReturnType<typeof setTimeout> | undefined;\n\n const cleanup = () => {\n clearTimeout(timeout);\n if (pendingCancellation) clearTimeout(pendingCancellation);\n unwatch();\n unsubscribeModal?.();\n };\n\n const timeout = setTimeout(() => {\n cleanup();\n reject(new Error(\"Connection timeout\"));\n }, 60000);\n\n const unwatch = watchAccount(config, {\n onChange: (account) => {\n if (account.address) {\n this.address = account.address;\n this.chainId = account.chainId;\n cleanup();\n resolve();\n }\n },\n });\n\n const modal = getAppKitModal();\n const unsubscribeModal = modal?.subscribeState((state) => {\n if (state.open) {\n modalHasOpened = true;\n if (pendingCancellation) {\n clearTimeout(pendingCancellation);\n pendingCancellation = undefined;\n }\n } else if (modalHasOpened) {\n const currentAccount = getAccount(config);\n if (currentAccount.address) {\n this.address = currentAccount.address;\n this.chainId = currentAccount.chainId;\n cleanup();\n resolve();\n return;\n }\n // Defer rejection so async handoffs (WalletConnect deep-link) can\n // still publish the connected account before we treat the close as a cancel.\n pendingCancellation = setTimeout(() => {\n const latestAccount = getAccount(config);\n if (latestAccount.address) {\n this.address = latestAccount.address;\n this.chainId = latestAccount.chainId;\n cleanup();\n resolve();\n } else {\n cleanup();\n reject(new Error(\"Connection cancelled\"));\n }\n }, MODAL_CLOSE_CANCEL_GRACE_MS);\n }\n });\n\n window.dispatchEvent(new CustomEvent(APPKIT_OPEN_EVENT));\n });\n\n await waitForConnection;\n return;\n }\n\n // Fallback to direct WalletConnect connection if event system not available\n const projectId = process.env.NEXT_PUBLIC_REOWN_PROJECT_ID;\n if (!projectId) {\n throw new Error(\"NEXT_PUBLIC_REOWN_PROJECT_ID environment variable is required\");\n }\n\n const wcConnector = walletConnect({\n projectId,\n metadata: {\n name: \"Babylon Vault\",\n description: \"\",\n url: \"\",\n icons: [\"\"],\n },\n });\n\n const result = await connect(config, { connector: wcConnector });\n this.address = result.accounts[0];\n this.chainId = result.chainId;\n } catch (error) {\n console.error(\"Failed to connect wallet:\", error instanceof Error ? error.message : \"Unknown error\");\n throw new Error(`Failed to connect wallet: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n }\n }\n\n async disconnect(scope: DisconnectScope): Promise<void> {\n if (scope === \"chain\" && ethDisconnectWouldDropBitcoin()) {\n throw new WalletError({\n code: ERROR_CODES.SHARED_SESSION_DISCONNECT_REFUSED,\n message:\n \"Ethereum and Bitcoin share one wallet session. Disconnecting Ethereum alone would also disconnect Bitcoin. Disconnect all wallets instead.\",\n wallet: \"AppKit\",\n chainId: \"ETH\",\n });\n }\n if (scope !== \"local\") await wagmiDisconnect(this.getWagmiConfig());\n this.address = undefined;\n this.chainId = undefined;\n }\n\n async getAddress(): Promise<string> {\n const config = this.getWagmiConfig();\n const account = getAccount(config);\n if (account.address) {\n this.address = account.address;\n this.chainId = account.chainId;\n return this.address;\n }\n\n if (this.address) {\n return this.address;\n }\n\n throw new Error(WALLET_NOT_CONNECTED_ERROR_MESSAGE);\n }\n\n async getPublicKeyHex(): Promise<string> {\n // ETH doesn't expose public keys directly like BTC\n // We return the address as the public identifier\n return this.getAddress();\n }\n\n async signMessage(message: string): Promise<string> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const signature = await wagmiSignMessage(config, {\n message,\n account: address as `0x${string}`,\n });\n return signature;\n } catch (error) {\n throw new Error(`Failed to sign message: ${error}`);\n }\n }\n\n async signTypedData(typedData: ETHTypedData): Promise<string> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const signature = await wagmiSignTypedData(config, {\n account: address as `0x${string}`,\n domain: {\n ...typedData.domain,\n salt: typedData.domain.salt as `0x${string}` | undefined,\n verifyingContract: typedData.domain.verifyingContract as `0x${string}` | undefined,\n },\n types: typedData.types,\n primaryType: typedData.primaryType,\n message: typedData.message,\n });\n return signature;\n } catch (error) {\n throw new Error(`Failed to sign typed data: ${error}`);\n }\n }\n\n async sendTransaction(tx: ETHTransactionRequest): Promise<string> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const hash = await wagmiSendTransaction(config, {\n account: address as `0x${string}`,\n to: tx.to as `0x${string}`,\n value: tx.value ? parseEther(tx.value) : undefined,\n data: tx.data as `0x${string}` | undefined,\n gas: tx.gasLimit,\n maxFeePerGas: tx.maxFeePerGas,\n maxPriorityFeePerGas: tx.maxPriorityFeePerGas,\n nonce: tx.nonce,\n });\n return hash;\n } catch (error) {\n throw new Error(`Failed to send transaction: ${error}`);\n }\n }\n\n async estimateGas(tx: ETHTransactionRequest): Promise<bigint> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const gas = await wagmiEstimateGas(config, {\n account: address as `0x${string}`,\n to: tx.to as `0x${string}`,\n value: tx.value ? parseEther(tx.value) : undefined,\n data: tx.data as `0x${string}` | undefined,\n });\n return gas;\n } catch (error) {\n throw new Error(`Failed to estimate gas: ${error}`);\n }\n }\n\n async getChainId(): Promise<number> {\n if (this.chainId) {\n return this.chainId;\n }\n\n const config = this.getWagmiConfig();\n const account = getAccount(config);\n if (account.chainId) {\n this.chainId = account.chainId;\n return this.chainId;\n }\n\n throw new Error(WALLET_NOT_CONNECTED_ERROR_MESSAGE);\n }\n\n async switchChain(chainId: number): Promise<void> {\n try {\n const config = this.getWagmiConfig();\n // Only allow switching to supported chains\n const supportedChains = [1, 11155111, 31337]; // Mainnet, Sepolia, and Anvil\n if (!supportedChains.includes(chainId)) {\n throw new Error(`Unsupported chain ID: ${chainId}`);\n }\n\n await wagmiSwitchChain(config, { chainId: chainId as 1 | 11155111 | 31337 });\n this.chainId = chainId;\n } catch (error) {\n throw new Error(`Failed to switch chain: ${error}`);\n }\n }\n\n async getBalance(): Promise<bigint> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const balance = await wagmiGetBalance(config, {\n address: address as `0x${string}`,\n });\n return balance.value;\n } catch (error) {\n throw new Error(`Failed to get balance: ${error}`);\n }\n }\n\n async getNonce(): Promise<number> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const nonce = await getTransactionCount(config, {\n address: address as `0x${string}`,\n });\n return nonce;\n } catch (error) {\n throw new Error(`Failed to get nonce: ${error}`);\n }\n }\n\n async getNetworkInfo(): Promise<NetworkInfo> {\n const chainId = await this.getChainId();\n return {\n name: this.config.chainName || \"Ethereum\",\n chainId: chainId.toString(),\n };\n }\n\n /**\n * Identity of the wallet the user actually connected through AppKit\n * (e.g. MetaMask, Rainbow), read from the active wagmi connector. Falls back\n * to a generic Ethereum identity when the connector doesn't expose its own.\n */\n private getActiveConnectorIdentity(): { name?: string; icon?: string } | undefined {\n // AppKit tracks the actual wallet the user connected (MetaMask, Rainbow, ...)\n // per chain namespace. The underlying wagmi connector usually reports a\n // generic \"WalletConnect\"/\"Injected\" identity, so prefer AppKit's view.\n const walletInfo = getAppKitModal()?.getWalletInfo(\"eip155\");\n if (walletInfo?.name || walletInfo?.icon) {\n return { name: walletInfo.name, icon: walletInfo.icon };\n }\n\n if (!hasSharedWagmiConfig()) return undefined;\n\n try {\n const { connector } = getAccount(this.getWagmiConfig());\n if (!connector) return undefined;\n\n return { name: connector.name, icon: connector.icon };\n } catch {\n return undefined;\n }\n }\n\n getWalletProviderName(): string {\n const name = this.getActiveConnectorIdentity()?.name;\n return name?.trim() ? name : ETH_FALLBACK_PROVIDER_NAME;\n }\n\n getWalletProviderIcon(): string {\n const icon = this.getActiveConnectorIdentity()?.icon;\n return icon?.trim() ? icon : ETH_FALLBACK_PROVIDER_ICON;\n }\n\n on(eventName: string, handler: (...args: any[]) => void): void {\n if (!this.eventHandlers.has(eventName)) {\n this.eventHandlers.set(eventName, new Set());\n }\n this.eventHandlers.get(eventName)!.add(handler);\n }\n\n off(eventName: string, handler: (...args: any[]) => void): void {\n const handlers = this.eventHandlers.get(eventName);\n if (handlers) {\n handlers.delete(handler);\n }\n }\n\n // Cleanup method for proper resource management\n destroy(): void {\n this.unwatchFunctions.forEach((unwatch) => unwatch());\n this.eventHandlers.clear();\n }\n}\n","import type { ETHConfig, IETHProvider, WalletMetadata } from \"@/core/types\";\nimport { Network } from \"@/core/types\";\nimport { APPKIT_ETH_CONNECTOR_ID } from \"@/core/wallets/appkit/constants\";\n\nimport { AppKitProvider } from \"./provider\";\n\nconst WALLET_PROVIDER_NAME = \"AppKit\";\n\nexport { APPKIT_ETH_CONNECTOR_ID };\n\n/**\n * AppKit wallet metadata for ETH chain\n *\n * Provides connection to 600+ Ethereum wallets through Reown's AppKit:\n * - MetaMask, Rainbow, WalletConnect, Coinbase Wallet, Trust Wallet, etc.\n * - Browser extension wallets (EIP-6963)\n * - Mobile wallets via WalletConnect\n * - Hardware wallets (Ledger, Trezor)\n */\nconst metadata: WalletMetadata<IETHProvider, ETHConfig> = {\n id: APPKIT_ETH_CONNECTOR_ID,\n name: WALLET_PROVIDER_NAME,\n icon: \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=\",\n docs: \"https://docs.reown.com/appkit/overview\",\n // No `wallet` global: AppKit reaches wallets through its own EIP-6963,\n // WalletConnect and hardware transports, none of which require an injected\n // `window.ethereum`. Gating on that global made every user without an EVM\n // browser extension (Safari, WalletConnect-QR, hardware-only) fail with\n // \"Provider not found\" before the AppKit modal could open — and ETH is a\n // required chain for deposit. Mirrors the BTC AppKit entry.\n wallet: undefined,\n createProvider: (_wallet: any, config: ETHConfig) => new AppKitProvider(config),\n networks: [\n Network.MAINNET, // ETH mainnet (chainId: 1)\n Network.TESTNET, // ETH testnet (chainId: 11155111 - Sepolia)\n Network.SIGNET, // Also allow SIGNET/devnet/localhost environments\n ],\n label: \"Connect ETH Wallet\",\n};\n\nexport default metadata;\n","export default \"data:image/svg+xml,%3csvg%20enable-background='new%200%200%201920%201920'%20viewBox='0%200%201920%201920'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='m959.8%2080.7-539.7%20895.6%20539.7-245.3z'%20fill='%238a92b2'/%3e%3cpath%20d='m959.8%20731-539.7%20245.3%20539.7%20319.1z'%20fill='%2362688f'/%3e%3cpath%20d='m1499.6%20976.3-539.8-895.6v650.3z'%20fill='%2362688f'/%3e%3cpath%20d='m959.8%201295.4%20539.8-319.1-539.8-245.3z'%20fill='%23454a75'/%3e%3cpath%20d='m420.1%201078.7%20539.7%20760.6v-441.7z'%20fill='%238a92b2'/%3e%3cpath%20d='m959.8%201397.6v441.7l540.1-760.6z'%20fill='%2362688f'/%3e%3c/svg%3e\"","import type { ChainMetadata, ETHConfig, IETHProvider } from \"@/core/types\";\n\nimport appkit from \"./appkit\";\nimport icon from \"./icon.svg\";\n\n/**\n * Ethereum chain metadata\n *\n * Defines the ETH chain configuration with available wallet providers.\n * Currently supports AppKit for connection to 600+ Ethereum wallets.\n */\nconst metadata: ChainMetadata<\"ETH\", IETHProvider, ETHConfig> = {\n chain: \"ETH\",\n name: \"Ethereum\",\n // icon: \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=\",\n icon,\n wallets: [appkit],\n};\n\nexport default metadata;\n","import { WagmiAdapter } from \"@reown/appkit-adapter-wagmi\";\nimport { createAppKit, modal as reownAppKitModal } from \"@reown/appkit/react\";\nimport { http, type Chain } from \"viem\";\nimport { cookieStorage, createStorage } from \"wagmi\";\nimport { baseAccount } from \"wagmi/connectors\";\n\nimport {\n assertAppKitCapabilities,\n createAppKitCapabilities,\n failInitialization,\n getAppKitState,\n setAppKitState,\n validateAppKitInitialization,\n} from \"@/core/wallets/appkit/state\";\n\nimport { getSharedWagmiConfig } from \"./sharedConfig\";\n\nexport interface AppKitMetadata {\n name: string;\n description: string;\n url: string;\n icons: string[];\n}\n\nexport interface AppKitModalConfig {\n projectId?: string;\n metadata: AppKitMetadata;\n eth: {\n /** ETH network chain configuration, from the host application's network config. */\n chain: Chain;\n };\n}\n\n/**\n * Builds the Ethereum adapter.\n *\n * The unified (ETH+BTC) initializer calls this too, so the Ethereum half of\n * AppKit is set up in exactly one place regardless of which entry point the\n * host imported.\n */\nexport function createETHWagmiAdapter(chain: Chain, projectId: string): WagmiAdapter {\n // Pin the transport to the chain's configured RPC URL. Without this, wagmi\n // falls back to viem's bundled public RPC (e.g. sepolia.drpc.org) which\n // doesn't see contracts on private/devnet deployments.\n const ethRpcUrl = chain.rpcUrls.default.http[0];\n // Supply the Base Account connector ourselves so AppKit skips constructing\n // its own default one. Its default enables the Base Account SDK's telemetry,\n // which injects an inline analytics script into the page.\n const adapter = new WagmiAdapter({\n networks: [chain],\n projectId,\n ssr: false,\n storage: createStorage({ storage: cookieStorage }),\n connectors: [baseAccount({ preference: { telemetry: false } })],\n transports: {\n [chain.id]: http(ethRpcUrl),\n },\n });\n\n return adapter;\n}\n\n/**\n * Initializes an Ethereum-only AppKit instance. Imports no Bitcoin adapter and\n * no Bitcoin network definitions, so it is safe to reach from the `./eth`\n * entry point.\n */\nexport function initializeAppKitModal(config: AppKitModalConfig) {\n if (!validateAppKitInitialization(config.projectId)) return null;\n\n const { chain } = config.eth;\n const capabilities = createAppKitCapabilities({\n projectId: config.projectId,\n metadata: config.metadata,\n ethChain: chain,\n });\n const existingState = getAppKitState();\n\n if (existingState) {\n assertAppKitCapabilities(existingState, capabilities);\n return { modal: existingState.modal, wagmiConfig: getSharedWagmiConfig() };\n }\n\n if (reownAppKitModal)\n failInitialization(\"Reown AppKit was initialized outside this package. Use only this package to initialize it.\");\n\n const wagmiAdapter = createETHWagmiAdapter(chain, config.projectId);\n\n const modal = createAppKit({\n adapters: [wagmiAdapter],\n networks: [chain],\n projectId: config.projectId,\n metadata: config.metadata,\n });\n const initializedState = setAppKitState({ modal, ...capabilities, wagmiConfig: wagmiAdapter.wagmiConfig });\n\n return { modal: initializedState.modal, wagmiConfig: wagmiAdapter.wagmiConfig };\n}\n","import { useEffect } from \"react\";\n\nimport { APPKIT_OPEN_EVENT } from \"@/core/wallets/appkit/constants\";\n// Read the modal from the shared singleton rather than from `appKitModal`,\n// which pulls the Bitcoin adapter in with it and would put Bitcoin code in the\n// `./eth` graph.\nimport { getAppKitModal } from \"@/core/wallets/appkit/state\";\n\n/**\n * Unified AppKit modal open listener\n *\n * Listens for AppKit open events and opens the unified AppKit modal.\n * Both ETH and BTC connectors dispatch the same event to open the modal.\n *\n * If AppKit modal is not initialized, the hook will silently ignore open requests.\n */\nexport const useAppKitOpenListener = () => {\n useEffect(() => {\n const handleOpenRequest = () => {\n try {\n const modal = getAppKitModal();\n\n if (modal) {\n modal.open();\n }\n } catch (error) {\n // AppKit not initialized or not available - log warning for diagnostics\n console.warn(\"AppKit modal not available:\", error);\n }\n };\n\n window.addEventListener(APPKIT_OPEN_EVENT, handleOpenRequest);\n return () => window.removeEventListener(APPKIT_OPEN_EVENT, handleOpenRequest);\n }, []);\n};\n","import { type Connectors, useChainProviders } from \"@/context/Chain.context\";\n\nexport type SupportedChains = keyof Connectors;\n\nexport function useChainConnector<K extends SupportedChains>(chainId: K) {\n const connectors = useChainProviders();\n\n return connectors?.[chainId] ?? null;\n}\n","import okxLogo from \"./icons/okx.svg\";\nimport { MONOCHROME_MARK_BACKGROUND } from \"./constants\";\n\n/**\n * AppKit reports the connected ETH wallet's own name and icon, and for wallets\n * we also support on Bitcoin that artwork differs from the asset we ship — OKX\n * returns a square tile where our Bitcoin asset is the circular mark, so one\n * wallet reads as two in the connected-wallet menu. Prefer our own asset for\n * those, keyed by name because that is the only identity AppKit exposes.\n */\nconst FIRST_PARTY_ICONS: { match: RegExp; icon: string; iconBackground?: string }[] = [\n { match: /okx/i, icon: okxLogo, iconBackground: MONOCHROME_MARK_BACKGROUND },\n];\n\nexport function resolveFirstPartyIcon(walletName: string) {\n return FIRST_PARTY_ICONS.find(({ match }) => match.test(walletName));\n}\n","import { useContext } from \"react\";\n\nimport { StateContext } from \"@/context/State.context\";\n\nexport const useWidgetState = () => useContext(StateContext);\n","import { useCallback, useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useChainProviders } from \"@/context/Chain.context\";\nimport { useLifeCycleHooks } from \"@/context/LifecycleHooks.context\";\nimport {\n confirmedChains,\n isConfirmationReceiptCovered,\n isLiveConfirmationReceiptValid,\n isValidConfirmationReceipt,\n subscribeToConfirmationIdentityChanges,\n WALLET_CONFIRMATION_RECEIPT_KEY,\n} from \"@/core/confirmationReceipt\";\nimport { ChainId, HashMap, IChain, IConnector, IETHProvider, IWallet, Network } from \"@/core/types\";\nimport { resolveFirstPartyIcon } from \"@/core/wallets/firstPartyIcons\";\nimport { ERROR_CODES, isSharedSessionRefusal, WalletError } from \"@/error\";\n\nimport { useWidgetState } from \"./useWidgetState\";\n\n/**\n * AppKit exposes a single generic \"Ethereum\" wallet entry, so the connected\n * wallet's static metadata carries a generic chain icon/name rather than the\n * actual wallet the user picked (MetaMask, Rainbow, ...). Re-resolve the\n * display identity from the provider, which reads it off the live wagmi\n * connector, so the selected-wallet UI shows the real wallet.\n */\nasync function resolveEthDisplayWallet(wallet: IWallet): Promise<IWallet> {\n const provider = wallet.provider as IETHProvider | null;\n if (!provider?.getWalletProviderName || !provider?.getWalletProviderIcon) return wallet;\n\n const [name, icon] = await Promise.all([provider.getWalletProviderName(), provider.getWalletProviderIcon()]);\n const firstParty = resolveFirstPartyIcon(name || wallet.name);\n\n return {\n id: wallet.id,\n name: name || wallet.name,\n icon: firstParty?.icon || icon || wallet.icon,\n iconBackground: firstParty?.iconBackground,\n docs: wallet.docs,\n installed: wallet.installed,\n provider: wallet.provider,\n account: wallet.account,\n label: wallet.label,\n hardware: wallet.hardware,\n };\n}\n\n/**\n * Connection-time WalletError codes that the user must see in-dialog —\n * silently bouncing back to chain selection would leave the user with no\n * idea why their wallet didn't connect.\n */\nconst TERMINAL_CONNECT_ERROR_CODES: ReadonlySet<string> = new Set([ERROR_CODES.INCOMPATIBLE_WALLET_VERSION]);\n\nexport interface BTCAddressValidation {\n validateAddress(network: Network, address: string): void;\n validateAddressWithPK(address: string, publicKey: string, network: Network): boolean;\n}\n\ninterface Props {\n persistent: boolean;\n accountStorage: HashMap;\n onError?: (e: Error) => void;\n btcValidation?: BTCAddressValidation;\n}\n\nexport function useWalletConnectors({ persistent, accountStorage, onError, btcValidation }: Props) {\n const connectors = useChainProviders();\n const {\n confirmed,\n confirmationReceipt,\n visible,\n selectWallet,\n removeWallet,\n displayLoader,\n displayChains,\n displayError,\n confirm,\n unconfirm,\n requiredChainIds = [],\n } = useWidgetState();\n const { verifyBTCAddress } = useLifeCycleHooks();\n const validationGenerationRef = useRef(0);\n const previousRequiredChainIdsRef = useRef(requiredChainIds);\n const confirmationCandidate =\n confirmationReceipt ?? (persistent && !visible ? accountStorage.get(WALLET_CONFIRMATION_RECEIPT_KEY) : undefined);\n const confirmationCandidateRef = useRef<string>();\n const dirtyOptionalChainsRef = useRef<Set<ChainId>>(new Set());\n const requiredConnectorsReady = requiredChainIds.every((chainId) => connectors[chainId as ChainId]?.connectedWallet);\n\n // A wallet that failed post-connect validation is forgotten locally no matter\n // what the provider does: the chain disconnect is attempted first so an\n // AppKit wallet is released, and a refusal (shared session) or a failure\n // falls back to the local teardown so the wallet cannot be selected again.\n const droppingRef = useRef<Set<string>>(new Set());\n const dropRejectedWallet = async (connector: Pick<IConnector, \"id\" | \"disconnect\">) => {\n droppingRef.current.add(connector.id);\n removeWallet?.(connector.id);\n if (persistent) accountStorage.delete(connector.id);\n try {\n await connector.disconnect(\"chain\");\n } catch (error) {\n if (!isSharedSessionRefusal(error)) {\n console.error(\n \"Failed to disconnect rejected wallet:\",\n error instanceof Error ? error.message : \"Unknown error\",\n );\n }\n await connector.disconnect(\"local\");\n } finally {\n droppingRef.current.delete(connector.id);\n }\n };\n\n // Connecting event\n useEffect(() => {\n if (!visible) return;\n\n const connectorArr = Object.values(connectors);\n\n const unsubscribeArr = connectorArr.filter(Boolean).map((connector) =>\n connector.on(\"connecting\", (message?: string, description?: string) => {\n displayLoader?.(message, description);\n }),\n );\n\n return () => unsubscribeArr.forEach((unsubscribe) => unsubscribe());\n }, [visible, displayLoader, connectors]);\n\n // Connect Event\n useEffect(() => {\n const connectorArr = Object.values(connectors).filter(Boolean);\n\n const handlers: Record<string, (connector: any) => (connectedWallet: IWallet) => void> = {\n BTC: (connector) => async (connectedWallet) => {\n try {\n if (!connectedWallet || !connectedWallet.account) return;\n if (!btcValidation) throw new Error(\"Bitcoin address validation is unavailable\");\n\n selectWallet?.(\"BTC\", connectedWallet);\n\n if (persistent && connectedWallet.account?.address) {\n accountStorage.set(connector.id, connectedWallet.id);\n }\n\n if (!visible) return;\n\n btcValidation.validateAddress(connector.config.network, connectedWallet.account.address);\n\n const goToNextScreen = () => void displayChains?.();\n\n if (\n !btcValidation.validateAddressWithPK(\n connectedWallet.account?.address ?? \"\",\n connectedWallet.account?.publicKeyHex ?? \"\",\n connector.config.network,\n )\n ) {\n displayError?.({\n title: \"Public Key Mismatch\",\n description:\n \"The Bitcoin address and Public Key for this wallet do not match. Please contact your wallet provider for support.\",\n onSubmit: goToNextScreen,\n onCancel: () => {\n void dropRejectedWallet(connector);\n displayChains?.();\n },\n });\n\n return;\n }\n\n if (verifyBTCAddress && !(await verifyBTCAddress(connectedWallet.account?.address ?? \"\"))) {\n displayError?.({\n title: \"Staking Currently Unavailable\",\n description:\n \"Staking is temporarily disabled due to network downtime. New stakes are paused until the network resumes.\",\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: async () => {\n void dropRejectedWallet(connector);\n displayChains?.();\n },\n });\n\n return;\n }\n\n goToNextScreen();\n } catch (e: any) {\n void dropRejectedWallet(connector);\n displayError?.({\n title: \"Connection Failed\",\n description: e.message,\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: async () => {\n displayChains?.();\n },\n });\n }\n },\n BBN: (connector) => (connectedWallet) => {\n if (connectedWallet) {\n selectWallet?.(connector.id, connectedWallet);\n\n if (persistent && connectedWallet.account?.address) {\n accountStorage.set(connector.id, connectedWallet.id);\n }\n }\n\n displayChains?.();\n },\n ETH: (connector) => async (connectedWallet) => {\n if (connectedWallet) {\n selectWallet?.(connector.id, await resolveEthDisplayWallet(connectedWallet));\n\n if (persistent && connectedWallet.account?.address) {\n accountStorage.set(connector.id, connectedWallet.id);\n }\n }\n\n displayChains?.();\n },\n };\n\n const unsubscribeArr = connectorArr.map((connector) =>\n connector.on(\"connect\", handlers[connector.id]?.(connector)),\n );\n\n connectorArr.forEach((connector) => {\n const connectedWallet = droppingRef.current.has(connector.id) ? null : connector.connectedWallet;\n if (connector.id === \"ETH\" && connectedWallet) {\n void resolveEthDisplayWallet(connectedWallet).then((wallet) => selectWallet?.(connector.id, wallet));\n return;\n }\n selectWallet?.(connector.id, connectedWallet);\n });\n\n return () => unsubscribeArr.forEach((unsubscribe) => unsubscribe());\n }, [\n onError,\n selectWallet,\n removeWallet,\n displayChains,\n displayError,\n verifyBTCAddress,\n btcValidation,\n accountStorage,\n connectors,\n persistent,\n visible,\n ]);\n\n // Disconnect Event\n useLayoutEffect(() => {\n const connectorArr = Object.values(connectors);\n\n const unsubscribeArr = connectorArr.filter(Boolean).map((connector) =>\n connector.on(\"disconnect\", (connectedWallet: IWallet) => {\n if (connectedWallet) {\n // Losing a required chain invalidates the confirmation it was part\n // of, so the receipt must not survive to auto-confirm a later\n // reconnect. An optional chain leaving is not a consent change.\n if (requiredChainIds.includes(connector.id)) {\n validationGenerationRef.current += 1;\n accountStorage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n }\n removeWallet?.(connector.id);\n displayChains?.();\n if (persistent) {\n accountStorage.delete(connector.id);\n }\n }\n }),\n );\n\n return () => unsubscribeArr.forEach((unsubscribe) => unsubscribe());\n }, [removeWallet, displayChains, connectors, persistent, accountStorage, requiredChainIds]);\n\n // Error Event\n useEffect(() => {\n const connectorArr = Object.values(connectors);\n\n const unsubscribeArr = connectorArr.filter(Boolean).map((connector) =>\n connector.on(\"error\", (error: Error) => {\n onError?.(error);\n\n // Terminal errors (e.g. the wallet extension is too old) need an\n // in-dialog message so the user can act on them. Anything else\n // falls through to the existing \"bounce back to chains\" behaviour\n // — host apps' `onError` callbacks still get the raw error.\n // Guard on `displayError` directly so we still fall through to\n // `displayChains?.()` below if the dialog state isn't wired up;\n // otherwise the user could be stranded on the current screen.\n if (error instanceof WalletError && TERMINAL_CONNECT_ERROR_CODES.has(error.code) && displayError) {\n const walletName = error.wallet ?? \"your wallet\";\n displayError({\n title: `Update ${walletName}`,\n description: error.message || `${walletName} needs to be updated before you can connect.`,\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: () => {\n displayChains?.();\n },\n });\n return;\n }\n\n displayChains?.();\n }),\n );\n\n return () => unsubscribeArr.forEach((unsubscribe) => unsubscribe());\n }, [onError, displayChains, displayError, connectors]);\n\n const validateConfirmation = useCallback(async () => {\n const generation = ++validationGenerationRef.current;\n if (!confirmationCandidate) return;\n\n if (!confirmationReceipt && !requiredConnectorsReady) return;\n\n const covered = await isLiveConfirmationReceiptValid(confirmationCandidate, requiredChainIds, connectors);\n if (generation !== validationGenerationRef.current) return;\n\n if (!covered) {\n accountStorage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n unconfirm?.();\n return;\n }\n\n if (!confirmed && !visible) {\n confirm?.(confirmationCandidate);\n displayChains?.();\n return;\n }\n\n // Keep the stored receipt alive with its confirmed session.\n if (persistent && confirmed) {\n accountStorage.set(WALLET_CONFIRMATION_RECEIPT_KEY, confirmationCandidate);\n }\n }, [\n accountStorage,\n confirmationCandidate,\n confirmationReceipt,\n confirmed,\n confirm,\n connectors,\n displayChains,\n persistent,\n requiredChainIds,\n requiredConnectorsReady,\n unconfirm,\n visible,\n ]);\n\n useEffect(() => {\n void validateConfirmation();\n }, [validateConfirmation]);\n\n useLayoutEffect(() => {\n const previousCandidate = confirmationCandidateRef.current;\n if (!confirmationCandidate || (previousCandidate && previousCandidate !== confirmationCandidate)) {\n dirtyOptionalChainsRef.current.clear();\n }\n confirmationCandidateRef.current = confirmationCandidate;\n }, [confirmationCandidate]);\n\n useLayoutEffect(() => {\n validationGenerationRef.current += 1;\n const newlyRequiredChainIds = requiredChainIds.filter(\n (chainId) => !previousRequiredChainIdsRef.current.includes(chainId),\n );\n previousRequiredChainIdsRef.current = requiredChainIds;\n if (!confirmationCandidate) return;\n\n const stopWatchingIdentity = subscribeToConfirmationIdentityChanges(\n confirmationCandidate,\n confirmedChains(confirmationCandidate),\n connectors,\n (chain) => {\n if (!requiredChainIds.includes(chain)) {\n dirtyOptionalChainsRef.current.add(chain);\n return;\n }\n\n validationGenerationRef.current += 1;\n accountStorage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n unconfirm?.();\n },\n );\n if (!confirmationReceipt && !requiredConnectorsReady) return stopWatchingIdentity;\n\n if (\n !isConfirmationReceiptCovered(confirmationCandidate, requiredChainIds, connectors) ||\n newlyRequiredChainIds.some((chainId) => dirtyOptionalChainsRef.current.has(chainId as ChainId)) ||\n (confirmationReceipt &&\n newlyRequiredChainIds.length > 0 &&\n !isValidConfirmationReceipt(confirmationCandidate, newlyRequiredChainIds, connectors))\n ) {\n stopWatchingIdentity();\n accountStorage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n unconfirm?.();\n return;\n }\n\n if (confirmationReceipt && newlyRequiredChainIds.length > 0) {\n unconfirm?.(true);\n }\n\n return stopWatchingIdentity;\n }, [\n accountStorage,\n confirmationCandidate,\n confirmationReceipt,\n connectors,\n requiredChainIds,\n requiredConnectorsReady,\n unconfirm,\n ]);\n\n useEffect(\n () => () => {\n validationGenerationRef.current += 1;\n },\n [],\n );\n\n const connect = useCallback(\n async (chain: IChain, wallet: IWallet) => {\n const connector = connectors[chain.id as keyof typeof connectors];\n await connector?.connect(wallet.id);\n },\n [connectors],\n );\n\n return { connect };\n}\n","import { useCallback, useMemo } from \"react\";\n\nimport { createExternalWallet } from \"@/core\";\nimport { ExternalConnector } from \"@/core/types\";\n\nexport function useWalletWidgets(connectors: any, config: any, onError?: (e: Error) => void) {\n const createChainWidget = useCallback(\n (chainId: string, externalConnectors: ExternalConnector[]) => (\n <>\n {externalConnectors.map(({ id, widget: Component }) => (\n <Component\n key={id}\n id={id}\n connector={connectors[chainId]}\n createWallet={createExternalWallet}\n onError={onError}\n />\n ))}\n </>\n ),\n [connectors, onError],\n );\n\n return useMemo(\n () =>\n config.reduce(\n (acc: Record<string, JSX.Element>, config: any) => ({\n ...acc,\n [config.chain]: createChainWidget(config.chain, config.connectors ?? []),\n }),\n {},\n ) as Record<string, JSX.Element>,\n [createChainWidget, config],\n );\n}\n","import { useCallback, useMemo } from \"react\";\n\nimport { useChainProviders } from \"@/context/Chain.context\";\nimport type { ChainId } from \"@/core/types\";\nimport { isSharedSessionRefusal } from \"@/error\";\n\nimport { useWidgetState } from \"./useWidgetState\";\n\nexport function useWalletConnect() {\n const {\n confirmed,\n chains: chainMap,\n requiredChainIds,\n selectedWallets,\n open: openModal,\n displayChains,\n displayError,\n displayWallets,\n reset,\n } = useWidgetState();\n const connectors = useChainProviders();\n\n /**\n * Opens the wallet dialog, on one chain's wallet list when given a chain.\n *\n * Deliberately does not `reset()`: attaching an optional chain to a session\n * that is already confirmed must not tear that session down. Requirement-set\n * changes are handled separately — `State.context` drops the confirmation\n * when a new required chain appears.\n */\n const open = useCallback(\n (chain?: ChainId) => {\n // Membership, not truthiness, for the same reason as `disconnect` below:\n // React's bivariant handler types let a consumer write `onClick={open}`,\n // which calls this with a MouseEvent. Testing the key explicitly means\n // that lands on the chain list rather than depending on a lookup miss.\n if (chain !== undefined && Object.prototype.hasOwnProperty.call(chainMap, chain)) {\n displayWallets?.(chain);\n } else {\n displayChains?.();\n }\n openModal?.();\n },\n [chainMap, displayChains, displayWallets, openModal],\n );\n\n /**\n * Disconnects a single chain, or every chain when called without one.\n *\n * A single-chain disconnect the provider refuses (the chain shares its\n * wallet session with another chain) is explained in the dialog and still\n * rejects, so the caller knows nothing was disconnected.\n *\n * Membership is tested rather than truthiness because React's bivariant\n * handler types let `onClick={disconnect}` pass a MouseEvent in here, which\n * must not be mistaken for a chain and silently skip the disconnect-all path.\n */\n const disconnect = useCallback(\n async (chain?: ChainId) => {\n if (chain !== undefined && Object.prototype.hasOwnProperty.call(connectors, chain)) {\n try {\n await connectors[chain]?.disconnect(\"chain\");\n } catch (error) {\n if (isSharedSessionRefusal(error)) {\n displayError?.({\n title: \"Wallets share one session\",\n description: error.message,\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: () => {\n displayChains?.();\n },\n });\n }\n throw error;\n }\n return;\n }\n\n for (const connector of Object.values(connectors)) {\n if (!connector) continue;\n\n await connector.disconnect(\"all\");\n }\n\n reset?.();\n },\n [connectors, displayChains, displayError, reset],\n );\n\n const selected = useMemo(\n () => requiredChainIds.every((chainId) => Boolean(selectedWallets[chainId])),\n [requiredChainIds, selectedWallets],\n );\n\n return {\n selected,\n connected: selected && confirmed,\n open,\n disconnect,\n };\n}\n","import { Avatar, Text } from \"@babylonlabs-io/core-ui\";\nimport type { JSX, PropsWithChildren } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\n\ninterface ChainButtonProps extends PropsWithChildren {\n className?: string;\n logo?: string | JSX.Element;\n title?: string | JSX.Element;\n alt?: string;\n onClick?: () => void;\n}\n\nexport function ChainButton({ className, alt, logo, title, children, onClick }: ChainButtonProps) {\n const avatar = typeof logo === \"string\" ? <Avatar url={logo} alt={alt} /> : <Avatar>{logo}</Avatar>;\n\n const getTestId = () => {\n if (typeof title === \"string\") {\n if (title.includes(\"Bitcoin\")) return \"select-bitcoin-wallet-button\";\n if (title.includes(\"Ethereum\")) return \"select-ethereum-wallet-button\";\n if (title.includes(\"Babylon\")) return \"select-babylon-wallet-button\";\n }\n return \"chain-button\";\n };\n\n return (\n <Text\n as=\"button\"\n className={twMerge(\n \"flex w-full cursor-pointer flex-col gap-4 rounded-lg bg-primary-contrast p-4 text-accent-primary\",\n className,\n )}\n onClick={onClick}\n data-testid={getTestId()}\n >\n <div className=\"flex w-full items-center gap-2.5\">\n <div className=\"flex items-center\">{avatar}</div>\n {title}\n\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n className=\"ml-auto block text-accent-secondary\"\n >\n <path\n d=\"M8.58984 16.59L13.1698 12L8.58984 7.41L9.99984 6L15.9998 12L9.99984 18L8.58984 16.59Z\"\n fill=\"currentColor\"\n />\n </svg>\n </div>\n\n {children && <div className=\"w-full\">{children}</div>}\n </Text>\n );\n}\n","import { CheckIcon, CopyIcon, Text, useCopy, WalletIcon } from \"@babylonlabs-io/core-ui\";\nimport { memo, type KeyboardEvent, type MouseEvent } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\n\ninterface ConnectedWalletProps {\n className?: string;\n logo: string;\n // See `IWallet.iconBackground`.\n logoBackground?: string;\n address: string;\n}\n\n// Addresses longer than this are middle-truncated (keep the head and tail) so\n// the user can verify the start and end at a glance. The full value is always\n// available via the `title` tooltip and the copy button.\nconst ADDRESS_TRUNCATE_THRESHOLD = 36;\nconst ADDRESS_EDGE_CHARS = 14;\n\nfunction truncateAddress(address: string) {\n if (address.length <= ADDRESS_TRUNCATE_THRESHOLD) return address;\n return `${address.slice(0, ADDRESS_EDGE_CHARS)}…${address.slice(-ADDRESS_EDGE_CHARS)}`;\n}\n\nexport const ConnectedWallet = memo(({ className, logo, logoBackground, address }: ConnectedWalletProps) => {\n const { isCopied, copyToClipboard } = useCopy();\n const copied = isCopied(address);\n\n // This row renders inside the clickable chain button, so stop propagation (and\n // use a span rather than a nested <button>) to keep the copy action isolated.\n const handleCopy = (e: MouseEvent | KeyboardEvent) => {\n e.stopPropagation();\n copyToClipboard(address, address);\n };\n\n return (\n <div className={twMerge(\"flex items-center gap-2.5 rounded-lg bg-secondary-highlight p-2\", className)}>\n <WalletIcon size=\"small\" className=\"shrink-0\" url={logo} background={logoBackground} />\n\n <Text\n as=\"div\"\n variant=\"caption\"\n title={address}\n className=\"min-w-0 flex-1 truncate text-left font-mono text-accent-secondary\"\n >\n {truncateAddress(address)}\n </Text>\n\n <span\n role=\"button\"\n tabIndex={0}\n aria-label={copied ? \"Address copied\" : \"Copy address\"}\n onClick={handleCopy}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \" \") handleCopy(e);\n }}\n className=\"flex shrink-0 cursor-pointer items-center text-accent-secondary hover:text-accent-primary\"\n >\n {copied ? <CheckIcon size={16} variant=\"success\" /> : <CopyIcon size={16} />}\n </span>\n </div>\n );\n});\n","import { Button, Heading, Text } from \"@babylonlabs-io/core-ui\";\nimport { memo } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\n\nimport { ChainButton } from \"@/components/ChainButton\";\nimport { ConnectedWallet } from \"@/components/ConnectedWallet\";\nimport type { IChain, IWallet } from \"@/core/types\";\n\nconst DISABLED_CONNECT_BG = \"disabled:!bg-[#CCCCCC] dark:disabled:!bg-secondary-strokeDark\";\n\nconst SELECT_WALLET_TITLE_PREFIX = \"Select \";\nconst SELECT_WALLET_TITLE_SUFFIX = \" Wallet\";\nconst OPTIONAL_CHAIN_TITLE_SUFFIX = \" (Optional)\";\n\ninterface ChainsProps {\n disabled?: boolean;\n chains: IChain[];\n /** Chains outside this set are labelled optional. Omit to label none. */\n requiredChainIds?: readonly string[];\n className?: string;\n selectedWallets?: Record<string, IWallet | undefined>;\n onConfirm?: () => void;\n onSelectChain?: (chain: IChain) => void;\n}\n\nexport const Chains = memo(\n ({\n disabled = false,\n chains,\n requiredChainIds,\n selectedWallets = {},\n className,\n onConfirm,\n onSelectChain,\n }: ChainsProps) => (\n <div\n className={twMerge(\n \"flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight text-accent-primary\",\n className,\n )}\n >\n <div className=\"border-b border-secondary-strokeLight p-6\">\n <Heading variant=\"h5\" className=\"text-accent-primary\">\n Connect Wallets\n </Heading>\n </div>\n\n <div className=\"flex flex-col gap-4 p-6\">\n <div className=\"flex flex-col gap-2\">\n {chains.map((chain) => {\n const selectedWallet = selectedWallets[chain.id];\n const optional = requiredChainIds !== undefined && !requiredChainIds.includes(chain.id);\n\n return (\n <ChainButton\n key={chain.id}\n title={`${SELECT_WALLET_TITLE_PREFIX}${chain.name}${SELECT_WALLET_TITLE_SUFFIX}${\n optional ? OPTIONAL_CHAIN_TITLE_SUFFIX : \"\"\n }`}\n logo={chain.icon}\n alt={chain.name}\n onClick={() => void onSelectChain?.(chain)}\n >\n {selectedWallet && (\n <ConnectedWallet\n logo={selectedWallet.icon}\n logoBackground={selectedWallet.iconBackground}\n address={selectedWallet.account?.address ?? \"\"}\n />\n )}\n </ChainButton>\n );\n })}\n\n <Button\n color=\"secondary\"\n disabled={disabled}\n fluid\n onClick={onConfirm}\n className={twMerge(\"text-sm disabled:!opacity-100\", DISABLED_CONNECT_BG)}\n data-testid=\"chains-connect-button\"\n >\n Connect\n </Button>\n </div>\n\n <Text variant=\"body2\" className=\"text-center text-accent-secondary\">\n By clicking Connect you agree with the{\" \"}\n <a\n href=\"https://babylonlabs.io/terms-of-use\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-accent-primary underline\"\n >\n Terms of Use\n </a>{\" \"}\n and{\" \"}\n <a\n href=\"https://babylonlabs.io/privacy-policy\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-accent-primary underline\"\n >\n Privacy Policy\n </a>\n .\n </Text>\n </div>\n </div>\n ),\n);\n","import { useCallback, useMemo } from \"react\";\n\nimport type { IChain } from \"@/core/types\";\n// Connector ids come from the shared constants module, not from each chain's\n// wallet metadata — importing the metadata here would put every Bitcoin wallet\n// adapter into the `./eth` graph, since this screen is part of the dialog.\nimport { useChainProviders } from \"@/context/Chain.context\";\nimport { APPKIT_BTC_CONNECTOR_ID, APPKIT_ETH_CONNECTOR_ID, APPKIT_OPEN_EVENT } from \"@/core/wallets/appkit/constants\";\nimport { ethDisconnectWouldDropBitcoin } from \"@/core/wallets/eth/appkit/sharedConfig\";\nimport { isSharedSessionRefusal } from \"@/error\";\nimport { useWalletConnect } from \"@/hooks/useWalletConnect\";\nimport { useWidgetState } from \"@/hooks/useWidgetState\";\n\nimport { Chains } from \"./index\";\n\n// AppKit's connectWallet() no-ops when the chain is already connected, so an\n// already-connected AppKit row would do nothing on click. Reopening the modal\n// directly lets the user switch accounts or disconnect to pick another wallet.\n// (Switching/disconnecting triggers the vault's reset-both-wallets policy.)\nfunction openAppKitModal() {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(APPKIT_OPEN_EVENT));\n }\n}\n\ninterface ContainerProps {\n className?: string;\n onConfirm?: () => void;\n}\n\nexport function ChainsContainer(props: ContainerProps) {\n const { chains, requiredChainIds, selectedWallets, displayWallets } = useWidgetState();\n const { selected, disconnect } = useWalletConnect();\n const connectors = useChainProviders();\n\n const chainArr = useMemo(() => Object.values(chains), [chains]);\n\n const handleSelectChain = useCallback(\n async (chain: IChain) => {\n if (chain.id === \"ETH\" || chain.id === \"BTC\") {\n const connector = connectors[chain.id];\n const appkitId = chain.id === \"ETH\" ? APPKIT_ETH_CONNECTOR_ID : APPKIT_BTC_CONNECTOR_ID;\n const wallet = connector?.wallets.find((candidate) => candidate.id === appkitId);\n if (wallet && connector?.wallets.length === 1) {\n const connected = Boolean(connector.connectedWallet);\n try {\n if (!connected) {\n await connector.connect(wallet.id);\n } else if (chain.id === \"ETH\" && !ethDisconnectWouldDropBitcoin()) {\n openAppKitModal();\n } else {\n await disconnect(chain.id);\n }\n } catch (error) {\n if (!isSharedSessionRefusal(error)) {\n console.error(\n `Failed to ${connected ? \"disconnect\" : \"connect\"} AppKit ${chain.id}:`,\n error instanceof Error ? error.message : \"Unknown error\",\n );\n }\n }\n return;\n }\n }\n\n // Normal flow for other chains or if chain has multiple wallets\n displayWallets?.(chain.id);\n },\n [displayWallets, connectors, disconnect],\n );\n\n return (\n <Chains\n disabled={!selected}\n chains={chainArr}\n requiredChainIds={requiredChainIds}\n selectedWallets={selectedWallets}\n onSelectChain={handleSelectChain}\n {...props}\n />\n );\n}\n","import { Button, DialogBody, DialogFooter, Heading, Text } from \"@babylonlabs-io/core-ui\";\nimport {} from \"react\";\n\ninterface ErrorProps {\n className?: string;\n icon?: JSX.Element;\n title: string | JSX.Element;\n description: string | JSX.Element;\n cancelButton?: string | JSX.Element;\n submitButton?: string | JSX.Element;\n onCancel?: () => void;\n onSubmit?: () => void;\n}\n\nconst DEFAULT_ICON = (\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"52\" height=\"52\" viewBox=\"0 0 52 52\" fill=\"none\">\n <path\n d=\"M2.16675 46.5837H49.8334L26.0001 5.41699L2.16675 46.5837ZM28.1667 40.0837H23.8334V35.7503H28.1667V40.0837ZM28.1667 31.417H23.8334V22.7503H28.1667V31.417Z\"\n fill=\"#387085\"\n />\n </svg>\n);\n\nexport function Error({\n className,\n icon = DEFAULT_ICON,\n title,\n description,\n cancelButton = \"Cancel\",\n submitButton = (\n <>\n Continue <span className=\"hidden md:inline\">Anyway</span>\n </>\n ),\n onCancel,\n onSubmit,\n}: ErrorProps) {\n return (\n <div className={className}>\n <DialogBody className=\"py-16 text-center\">\n <div className=\"mb-6 inline-flex size-20 items-center justify-center bg-primary-contrast text-primary-light\">\n {icon}\n </div>\n\n <Heading variant=\"h4\" className=\"mb-4 text-accent-primary\">\n {title}\n </Heading>\n\n <Text as=\"div\" className=\"text-accent-secondary\">\n {description}\n </Text>\n </DialogBody>\n\n <DialogFooter className=\"flex gap-4\">\n {cancelButton && (\n <Button variant=\"outlined\" fluid onClick={onCancel}>\n {cancelButton}\n </Button>\n )}\n\n {submitButton && (\n <Button fluid onClick={onSubmit} data-testid=\"error-continue-button\">\n {submitButton}\n </Button>\n )}\n </DialogFooter>\n </div>\n );\n}\n","import { useWidgetState } from \"@/hooks/useWidgetState\";\n\nimport { Error } from \"./index\";\n\ninterface ErrorContainer {\n className?: string;\n}\n\nexport function ErrorContainer({ className }: ErrorContainer) {\n const { screen } = useWidgetState();\n const { icon, title, description, cancelButton, submitButton, onCancel, onSubmit } = screen.params ?? {};\n\n return (\n <Error\n className={className}\n icon={icon}\n title={title}\n description={description}\n cancelButton={cancelButton}\n submitButton={submitButton}\n onCancel={onCancel}\n onSubmit={onSubmit}\n />\n );\n}\n","import { Heading, Loader, Text } from \"@babylonlabs-io/core-ui\";\nimport { twMerge } from \"tailwind-merge\";\n\ninterface LoaderProps {\n className?: string;\n title?: string;\n description?: string;\n}\n\nexport function LoaderScreen({ className, title, description }: LoaderProps) {\n return (\n <div className={twMerge(\"flex flex-col items-center justify-center gap-6\", className)}>\n <div className=\"flex items-center justify-center bg-primary-contrast p-6\">\n <Loader className=\"text-primary-light\" />\n </div>\n {(title || description) && (\n <div className=\"flex flex-col items-center gap-2 text-center\">\n {title && (\n <Heading variant=\"h4\" className=\"capitalize text-accent-primary\">\n {title}\n </Heading>\n )}\n {description && (\n <Text as=\"div\" className=\"text-accent-secondary\">\n {description}\n </Text>\n )}\n </div>\n )}\n </div>\n );\n}\n","import { Chip, Text, WalletIcon } from \"@babylonlabs-io/core-ui\";\nimport { twMerge } from \"tailwind-merge\";\n\n// Green = software wallet detected/installed; yellow = hardware wallet that is\n// available but still needs connecting; secondary/gray = not installed.\nconst INSTALLED_ACCENT = \"text-[#15B768] dark:text-[#00E676]\";\nconst INSTALLED_DOT = \"bg-[#15B768] dark:bg-[#00E676]\";\nconst HARDWARE_ACCENT = \"text-[#FFB300]\";\nconst HARDWARE_DOT = \"bg-[#FFB300]\";\n\ninterface WalletButtonProps {\n className?: string;\n logo: string;\n // See `IWallet.iconBackground`.\n logoBackground?: string;\n disabled?: boolean;\n name: string;\n fallbackLink?: string;\n installed?: boolean;\n hardware?: boolean;\n label?: string;\n onClick?: () => void;\n}\n\nexport function WalletButton({\n className,\n disabled = false,\n name,\n logo,\n logoBackground,\n fallbackLink,\n installed = true,\n hardware = false,\n label,\n onClick,\n}: WalletButtonProps) {\n // Hardware wallets are always reachable through the connect flow (they have no\n // browser-extension detection step), so they show a yellow \"available\" badge\n // instead of the detection-based Installed/Uninstalled one, and are clickable\n // even when no provider is detected.\n const reachable = installed || hardware;\n const btnProps = reachable\n ? { as: \"button\", disabled, onClick }\n : { as: \"a\", href: fallbackLink, target: \"_blank\", rel: \"noopener noreferrer\" };\n\n const getTestId = () => {\n const normalizedName = name.toLowerCase();\n if (normalizedName.includes(\"okx\")) return \"wallet-option-okx\";\n if (normalizedName.includes(\"keplr\")) return \"wallet-option-keplr\";\n if (normalizedName.includes(\"leap\")) return \"wallet-option-leap\";\n return `wallet-option-${normalizedName.replace(/\\s+/g, \"-\")}`;\n };\n\n return (\n <Text\n variant=\"body2\"\n className={twMerge(\n \"flex h-14 w-full items-center gap-2.5 rounded-lg p-2 text-accent-primary\",\n installed ? \"bg-neutral-200\" : \"bg-neutral-100\",\n disabled ? \"cursor-default\" : \"cursor-pointer\",\n className,\n )}\n {...btnProps}\n data-testid={getTestId()}\n >\n <WalletIcon className=\"shrink-0\" alt={name} url={logo} background={logoBackground} />\n <span className={twMerge(\"min-w-0 flex-1 truncate text-left\", !installed && \"text-accent-secondary\")}>{name}</span>\n\n <Chip\n className={twMerge(\n \"flex shrink-0 items-center gap-1.5 rounded-full\",\n installed ? \"bg-neutral-100\" : \"bg-neutral-200\",\n )}\n >\n {(hardware || installed) && (\n <span className={twMerge(\"size-2 rounded-full\", hardware ? HARDWARE_DOT : INSTALLED_DOT)} />\n )}\n <span className={hardware ? HARDWARE_ACCENT : installed ? INSTALLED_ACCENT : \"text-accent-secondary\"}>\n {hardware ? label : installed ? \"Installed\" : \"Uninstalled\"}\n </span>\n </Chip>\n </Text>\n );\n}\n","import { Heading, Text } from \"@babylonlabs-io/core-ui\";\nimport { memo, useCallback, useMemo } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\n\nimport { WalletButton } from \"@/components/WalletButton\";\nimport { type BTCConfig, type IChain, type IWallet, Network } from \"@/core/types\";\n\nconst TAPROOT_ADDRESS_PREFIX: Record<Network, string> = {\n [Network.MAINNET]: \"bc1p\",\n [Network.TESTNET]: \"tb1p\",\n [Network.SIGNET]: \"tb1p\",\n};\n\n// Where depositors without testnet coins can request signet BTC. Only surfaced\n// on non-mainnet networks, where the \"testnet BTC\" prompt is meaningful.\nconst BTC_TESTNET_FAUCET_URL = \"https://tbv-faucet.testnet.babylonlabs.io/\";\n\nexport interface WalletsProps {\n chain: IChain;\n className?: string;\n append?: JSX.Element;\n onSelectWallet?: (chain: IChain, wallet: IWallet) => void;\n}\n\n// Connect-list ordering: installed software wallets (green) first, then\n// hardware wallets (yellow — available but need connecting), then uninstalled\n// download-only options (gray) at the bottom. A lower rank sorts higher, so\n// when no software wallet is installed the hardware options surface to the top.\nconst walletDisplayRank = (wallet: IWallet): number => {\n if (wallet.installed && !wallet.hardware) return 0;\n if (wallet.hardware) return 1;\n return 2;\n};\n\nexport const Wallets = memo(({ chain, className, append, onSelectWallet }: WalletsProps) => {\n const wallets = useMemo(\n () =>\n chain.wallets\n .filter((wallet) => (wallet.id === \"injectable\" ? wallet.installed : true))\n .sort((a, b) => walletDisplayRank(a) - walletDisplayRank(b)),\n [chain],\n );\n\n // Taproot is a hard requirement for the BTC vault, so surface the expected\n // address prefix for the connected network (bc1p on mainnet, tb1p otherwise).\n // The faucet prompt only makes sense off mainnet, where testnet coins apply.\n const btcHint = useMemo(() => {\n if (chain.id !== \"BTC\") return null;\n\n const network = (chain.config as BTCConfig | undefined)?.network;\n const prefix = network ? TAPROOT_ADDRESS_PREFIX[network] : undefined;\n if (!prefix) return null;\n\n return { prefix, showFaucet: network !== Network.MAINNET };\n }, [chain]);\n\n const handleWalletClick = useCallback(\n async (wallet: IWallet) => {\n onSelectWallet?.(chain, wallet);\n },\n [chain, onSelectWallet],\n );\n\n return (\n <div className={twMerge(\"flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight\", className)}>\n <div className=\"flex flex-col gap-2 border-b border-secondary-strokeLight p-6\">\n <Heading variant=\"h5\" className=\"text-accent-primary\">\n {`Select ${chain.name} Wallet`}\n </Heading>\n {btcHint && (\n <Text variant=\"body2\" className=\"text-accent-secondary\">\n {`To continue, connect a ${chain.name} wallet with a `}\n <span className=\"text-accent-primary\">{`${btcHint.prefix} (Taproot)`}</span>\n {\" address.\"}\n {btcHint.showFaucet && (\n <>\n {\" Don't have testnet BTC yet? Get it from \"}\n <a\n href={BTC_TESTNET_FAUCET_URL}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-accent-primary underline underline-offset-2 transition-opacity hover:opacity-80\"\n >\n Faucet\n </a>\n {\".\"}\n </>\n )}\n </Text>\n )}\n </div>\n\n <div className=\"flex flex-col gap-4 p-6\">\n {wallets.map((wallet) => (\n <WalletButton\n installed={wallet.installed}\n hardware={wallet.hardware}\n label={wallet.label}\n key={wallet.id}\n name={wallet.name}\n logo={wallet.icon}\n logoBackground={wallet.iconBackground}\n fallbackLink={wallet.docs}\n onClick={() => handleWalletClick(wallet)}\n />\n ))}\n\n {append}\n </div>\n </div>\n );\n});\n","import { type JSX } from \"react\";\n\nimport type { IChain, IWallet } from \"@/core/types\";\nimport { useWidgetState } from \"@/hooks/useWidgetState\";\n\nimport { Wallets } from \"./index\";\n\ninterface WalletContainerProps {\n widgets?: Record<string, JSX.Element | undefined>;\n className?: string;\n append?: JSX.Element;\n onSelectWallet?: (chain: IChain, wallet: IWallet) => void;\n}\n\nexport function WalletsContainer({ widgets = {}, ...props }: WalletContainerProps) {\n const { chains, screen } = useWidgetState();\n const chainId = screen.params?.chain ?? \"\";\n const currentChain = chains?.[chainId];\n const widget = widgets?.[chainId];\n\n return <Wallets append={widget} chain={currentChain} {...props} />;\n}\n","import { type JSX } from \"react\";\n\nimport { ChainsContainer as Chains } from \"@/components/Chains/container\";\nimport { ErrorContainer as Error } from \"@/components/Error/container\";\nimport { LoaderScreen } from \"@/components/Loader\";\nimport { WalletsContainer as Wallets } from \"@/components/Wallets/container\";\nimport type { Screen } from \"@/context/State.context\";\nimport type { IChain, IWallet } from \"@/core/types\";\n\ninterface ScreenProps {\n current: Screen;\n widgets?: Record<string, JSX.Element | undefined>;\n onSelectWallet?: (chain: IChain, wallet: IWallet) => void;\n onConfirm?: () => void;\n}\n\nconst SCREENS = {\n CHAINS: ({ onConfirm }: ScreenProps) => <Chains onConfirm={onConfirm} />,\n WALLETS: ({ widgets, onSelectWallet }: ScreenProps) => <Wallets widgets={widgets} onSelectWallet={onSelectWallet} />,\n LOADER: ({ current }: ScreenProps) => (\n <LoaderScreen title={current?.params?.message as string} description={current?.params?.description as string} />\n ),\n ERROR: () => <Error />,\n EMPTY: () => <div />,\n} as const;\n\nexport function Screen(props: ScreenProps) {\n const CurrentScreen = SCREENS[props.current.type as keyof typeof SCREENS] ?? SCREENS.EMPTY;\n\n return <CurrentScreen {...props} />;\n}\n","import { FullScreenDialog } from \"@babylonlabs-io/core-ui\";\nimport { useCallback, useLayoutEffect, useRef, type ReactNode } from \"react\";\n\nimport { useChainProviders, type Connectors } from \"@/context/Chain.context\";\nimport { useLifeCycleHooks, type WalletLifecycleConnection } from \"@/context/LifecycleHooks.context\";\nimport {\n confirmedChains,\n createConfirmationReceipt,\n sameIdentity,\n subscribeToConfirmationIdentityChanges,\n WALLET_CONFIRMATION_RECEIPT_KEY,\n} from \"@/core/confirmationReceipt\";\nimport type { ChainId, HashMap, IBTCProvider, IETHProvider, IWallet } from \"@/core/types\";\nimport { useWalletConnectors, type BTCAddressValidation } from \"@/hooks/useWalletConnectors\";\nimport { useWalletWidgets } from \"@/hooks/useWalletWidgets\";\nimport { useWidgetState } from \"@/hooks/useWidgetState\";\n\nimport { Screen } from \"./Screen\";\n\nconst WALLET_CHANGED_ERROR_MESSAGE = \"Wallet changed while confirming\";\nconst WALLET_NETWORK_MISSING_ERROR_MESSAGE = \"Wallet did not report its network\";\nconst WALLET_NETWORK_MISMATCH_ERROR_MESSAGE = \"Wallet network does not match the configured network\";\nconst WALLET_PROVIDER_MISSING_ERROR_MESSAGE = \"Connected wallet has no provider\";\n\n/**\n * Picks the identity the terms-of-service hook is called with. Required chains\n * are walked in the host's declared order. Connector order can differ from it.\n */\nfunction findPrimaryConnection(\n connections: WalletLifecycleConnection[],\n requiredChainIds: string[],\n): WalletLifecycleConnection | undefined {\n for (const chainId of requiredChainIds) {\n const match = connections.find(({ chain }) => chain === chainId);\n if (match) return match;\n }\n\n return connections[0];\n}\n\nfunction collectConnections(connectors: Connectors): WalletLifecycleConnection[] {\n return Object.entries(connectors).flatMap<WalletLifecycleConnection>(([chain, connector]) => {\n const wallet = connector?.connectedWallet;\n return wallet?.account ? [{ chain: chain as ChainId, wallet, account: { ...wallet.account } }] : [];\n });\n}\n\nfunction copyConnections(connections: WalletLifecycleConnection[]): WalletLifecycleConnection[] {\n return connections.map(({ chain, wallet, account }) => {\n const accountCopy = { ...account };\n const walletCopy: IWallet = {\n id: wallet.id,\n name: wallet.name,\n icon: wallet.icon,\n iconBackground: wallet.iconBackground,\n docs: wallet.docs,\n installed: wallet.installed,\n provider: wallet.provider,\n account: accountCopy,\n label: wallet.label,\n hardware: wallet.hardware,\n };\n\n return { chain, wallet: walletCopy, account: accountCopy };\n });\n}\n\ninterface ConnectionIdentity {\n chain: ChainId;\n wallet: IWallet;\n provider: IWallet[\"provider\"];\n receipt: string;\n}\n\nfunction hasSameIdentity(\n expected: readonly ConnectionIdentity[],\n current: readonly ConnectionIdentity[],\n requiredChainIds: readonly string[],\n): boolean {\n return expected.every(({ chain, wallet, provider, receipt }) => {\n const match = current.find((identity) => identity.chain === chain);\n if (!match) return !requiredChainIds.includes(chain);\n\n return match.wallet === wallet && match.provider === provider && match.receipt === receipt;\n });\n}\n\nasync function createConfirmationSnapshot(\n getConnectors: () => Connectors,\n requiredChainIds: readonly string[],\n onOptionalError?: (error: Error) => void,\n): Promise<{\n receipt: string;\n connections: WalletLifecycleConnection[];\n identities: readonly ConnectionIdentity[];\n}> {\n const connectors = getConnectors();\n const candidates = collectConnections(connectors).map((connection) => ({\n connection,\n provider: connection.wallet.provider,\n receipt: createConfirmationReceipt([connection], connectors),\n }));\n\n const results = await Promise.all(\n candidates.map(async (candidate) => {\n const { chain } = candidate.connection;\n const { provider } = candidate;\n\n try {\n if (!provider) throw new Error(`${WALLET_PROVIDER_MISSING_ERROR_MESSAGE}: ${chain}`);\n\n if (provider.isIdentityCurrent?.() === false) {\n throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n }\n\n let network: string | number | undefined;\n if (chain === \"ETH\" || chain === \"BTC\") {\n // Fixed-network providers report their operational network here. They\n // have no independent wallet network that the user can switch.\n network =\n chain === \"ETH\"\n ? await (provider as IETHProvider).getChainId()\n : await (provider as IBTCProvider).getNetwork();\n if (network === undefined || network === null || !String(network)) {\n throw new Error(WALLET_NETWORK_MISSING_ERROR_MESSAGE);\n }\n\n const liveReceipt = createConfirmationReceipt([candidate.connection], connectors, { [chain]: network });\n if (liveReceipt !== candidate.receipt) {\n throw new Error(WALLET_NETWORK_MISMATCH_ERROR_MESSAGE);\n }\n }\n\n const [address, publicKeyHex] = await Promise.all([provider.getAddress(), provider.getPublicKeyHex()]);\n if (\n !address ||\n !publicKeyHex ||\n !sameIdentity(address, candidate.connection.account.address) ||\n !sameIdentity(publicKeyHex, candidate.connection.account.publicKeyHex)\n ) {\n throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n }\n\n if (provider.isIdentityCurrent?.() === false) {\n throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n }\n\n // IBBNProvider has no network getter. Its live account identity is\n // still checked above.\n return {\n ...candidate,\n connection: { ...candidate.connection, account: { address, publicKeyHex } },\n };\n } catch (error) {\n if (requiredChainIds.includes(chain)) throw error;\n onOptionalError?.(error instanceof Error ? error : new Error(\"Optional wallet verification failed\"));\n return null;\n }\n }),\n );\n\n const verifiedCandidates = results.filter(\n (candidate): candidate is (typeof candidates)[number] => candidate !== null,\n );\n const settledConnectors = getConnectors();\n const settledConnections = collectConnections(settledConnectors);\n const stableCandidates = verifiedCandidates.flatMap((candidate) => {\n const { connection, receipt } = candidate;\n const settled = settledConnections.find(({ chain }) => chain === connection.chain);\n const stable = Boolean(\n settled &&\n settled.wallet === connection.wallet &&\n settled.wallet.provider === candidate.provider &&\n createConfirmationReceipt([settled], settledConnectors) === receipt,\n );\n\n if (stable) return [candidate];\n if (requiredChainIds.includes(connection.chain)) throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n onOptionalError?.(new Error(WALLET_CHANGED_ERROR_MESSAGE));\n return [];\n });\n const connections = stableCandidates.map(({ connection }) => connection);\n const identities = stableCandidates.map(({ connection, provider, receipt }) => ({\n chain: connection.chain,\n wallet: connection.wallet,\n provider,\n receipt,\n }));\n\n // Restore stays synchronous until #2351 adds live session checks. Store this\n // configured receipt only after it equals the live network identity.\n return {\n receipt: createConfirmationReceipt(connections, settledConnectors),\n connections,\n identities: Object.freeze(identities),\n };\n}\n\ninterface WalletDialogProps {\n onError?: (e: Error) => void;\n btcValidation?: BTCAddressValidation;\n storage: HashMap;\n config: any;\n persistent: boolean;\n /** Optional content rendered top-right, mirroring the close/back button (e.g. a settings trigger). */\n actions?: ReactNode;\n /** Overrides the default `left-4` position of the close/back button. */\n closeButtonClassName?: string;\n /** Overrides the default `right-4` position of the `actions` slot. */\n actionsClassName?: string;\n}\n\nexport function WalletDialog({\n persistent,\n storage,\n config,\n onError,\n btcValidation,\n actions,\n closeButtonClassName,\n actionsClassName,\n}: WalletDialogProps) {\n const { visible, screen, confirmed, requiredChainIds, close, confirm, unconfirm, displayChains, displayError } =\n useWidgetState();\n const { acceptTermsOfService, onConfirm } = useLifeCycleHooks();\n const connectors = useChainProviders();\n const walletWidgets = useWalletWidgets(connectors, config, onError);\n const { connect } = useWalletConnectors({ persistent, accountStorage: storage, onError, btcValidation });\n\n const connectorsRef = useRef(connectors);\n const attemptGenerationRef = useRef(0);\n const activeAttemptRef = useRef<number | null>(null);\n const activeIdentitySubscriptionRef = useRef<(() => void) | null>(null);\n const mountedRef = useRef(false);\n const visibleRef = useRef(visible);\n const confirmedRef = useRef(confirmed);\n const confirmationInputsRef = useRef({ persistent, requiredChainIds: [...requiredChainIds], storage });\n\n const invalidateAttempt = useCallback(() => {\n const stopWatchingIdentity = activeIdentitySubscriptionRef.current;\n activeIdentitySubscriptionRef.current = null;\n attemptGenerationRef.current += 1;\n activeAttemptRef.current = null;\n stopWatchingIdentity?.();\n }, []);\n\n useLayoutEffect(() => {\n connectorsRef.current = connectors;\n if ((visibleRef.current && !visible) || (!confirmedRef.current && confirmed)) invalidateAttempt();\n visibleRef.current = visible;\n confirmedRef.current = confirmed;\n }, [confirmed, connectors, invalidateAttempt, visible]);\n\n useLayoutEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n invalidateAttempt();\n };\n }, [invalidateAttempt]);\n\n useLayoutEffect(() => {\n const previous = confirmationInputsRef.current;\n const requiredChainsChanged =\n previous.requiredChainIds.length !== requiredChainIds.length ||\n previous.requiredChainIds.some((chainId, index) => chainId !== requiredChainIds[index]);\n\n if (previous.persistent !== persistent || previous.storage !== storage || requiredChainsChanged) {\n invalidateAttempt();\n }\n confirmationInputsRef.current = { persistent, requiredChainIds: [...requiredChainIds], storage };\n }, [invalidateAttempt, persistent, requiredChainIds, storage]);\n\n // Closing without confirming leaves the connectors connected, so the user can\n // reopen and finish where they left off. The receipt written on confirm is\n // the single gate that lets a later reload auto-confirm — no receipt, no\n // silent restore — so leaving the connection up grants nothing on its own.\n const handleClose = useCallback(() => {\n invalidateAttempt();\n close?.();\n }, [close, invalidateAttempt]);\n\n const handleConfirm = useCallback(async () => {\n if (activeAttemptRef.current !== null || !mountedRef.current || !visibleRef.current) return;\n\n const generation = attemptGenerationRef.current + 1;\n attemptGenerationRef.current = generation;\n activeAttemptRef.current = generation;\n const isCurrentAttempt = () =>\n activeAttemptRef.current === generation &&\n attemptGenerationRef.current === generation &&\n mountedRef.current &&\n visibleRef.current;\n let stopWatchingIdentity = () => {};\n let confirmationHandoffPending = false;\n\n try {\n if (!confirmed) {\n const initialConnectors = connectorsRef.current;\n const initialReceipt = createConfirmationReceipt(collectConnections(initialConnectors), initialConnectors);\n const unsubscribeIdentity = subscribeToConfirmationIdentityChanges(\n initialReceipt,\n confirmedChains(initialReceipt),\n initialConnectors,\n () => {\n invalidateAttempt();\n storage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n unconfirm?.();\n },\n );\n let watchingIdentity = true;\n stopWatchingIdentity = () => {\n if (!watchingIdentity) return;\n watchingIdentity = false;\n unsubscribeIdentity();\n };\n if (!isCurrentAttempt()) {\n stopWatchingIdentity();\n return;\n }\n activeIdentitySubscriptionRef.current = stopWatchingIdentity;\n\n const confirmationSnapshot = await createConfirmationSnapshot(\n () => connectorsRef.current,\n requiredChainIds,\n onError,\n );\n if (!isCurrentAttempt()) return;\n const { connections } = confirmationSnapshot;\n\n // A required chain whose connector has no active account would\n // otherwise drop silently out of `connections` and be confirmed with\n // nothing recorded for it, leaving the next reload to ask again with no\n // signal that anything went wrong.\n const uncovered = requiredChainIds.filter((chainId) => !connections.some(({ chain }) => chain === chainId));\n if (uncovered.length > 0) {\n throw new Error(\n `No connected account for required chain${uncovered.length > 1 ? \"s\" : \"\"}: ${uncovered.join(\", \")}`,\n );\n }\n\n const primary = findPrimaryConnection(connections, requiredChainIds);\n const checkIdentity = async () => {\n if (!isCurrentAttempt()) return false;\n\n const currentSnapshot = await createConfirmationSnapshot(\n () => connectorsRef.current,\n requiredChainIds,\n onError,\n );\n if (!isCurrentAttempt()) return false;\n\n if (!hasSameIdentity(confirmationSnapshot.identities, currentSnapshot.identities, requiredChainIds)) {\n throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n }\n\n return true;\n };\n\n if (primary) {\n await acceptTermsOfService?.({\n address: primary.account.address,\n public_key: primary.account.publicKeyHex,\n chain: primary.chain,\n connections: copyConnections(connections),\n });\n if (!(await checkIdentity())) return;\n }\n await onConfirm?.(copyConnections(connections));\n if (!(await checkIdentity())) return;\n\n if (persistent) {\n storage.set(WALLET_CONFIRMATION_RECEIPT_KEY, confirmationSnapshot.receipt);\n }\n\n if (!isCurrentAttempt()) return;\n confirm?.(confirmationSnapshot.receipt);\n if (!isCurrentAttempt()) return;\n confirmationHandoffPending = Boolean(confirm);\n }\n\n if (!isCurrentAttempt()) return;\n close?.();\n } catch (error) {\n if (!isCurrentAttempt()) return;\n\n const normalizedError = error instanceof Error ? error : new Error(\"Wallet confirmation failed\");\n onError?.(normalizedError);\n if (!isCurrentAttempt()) return;\n displayError?.({\n title: \"Connection Failed\",\n description: normalizedError.message,\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: displayChains,\n });\n } finally {\n if (!confirmationHandoffPending) {\n stopWatchingIdentity();\n if (activeIdentitySubscriptionRef.current === stopWatchingIdentity) {\n activeIdentitySubscriptionRef.current = null;\n }\n if (attemptGenerationRef.current === generation && activeAttemptRef.current === generation) {\n activeAttemptRef.current = null;\n }\n }\n }\n }, [\n acceptTermsOfService,\n close,\n confirm,\n confirmed,\n displayChains,\n displayError,\n invalidateAttempt,\n onConfirm,\n onError,\n persistent,\n requiredChainIds,\n storage,\n unconfirm,\n ]);\n\n const onBack = screen.type === \"WALLETS\" ? displayChains : undefined;\n\n return (\n <FullScreenDialog\n open={visible}\n onClose={handleClose}\n onBack={onBack}\n className=\"items-center justify-center p-6\"\n actions={actions}\n closeButtonClassName={closeButtonClassName}\n actionsClassName={actionsClassName}\n >\n <div className=\"mx-auto w-full max-w-[612px]\">\n <Screen current={screen} widgets={walletWidgets} onConfirm={handleConfirm} onSelectWallet={connect} />\n </div>\n </FullScreenDialog>\n );\n}\n","import { useEffect, useRef } from \"react\";\n\ninterface UseVisibilityCheckOptions {\n /** Whether the visibility check is enabled */\n enabled: boolean;\n /** Delay in ms before running the check (default: 500) */\n delay?: number;\n}\n\n/**\n * Runs a callback when the document becomes visible.\n * Useful for checking wallet connections when user returns to the tab.\n */\nexport function useVisibilityCheck(\n onVisible: () => void | Promise<void>,\n options: UseVisibilityCheckOptions,\n) {\n const { enabled, delay = 500 } = options;\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n if (!enabled) return;\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n\n const handleVisibilityChange = () => {\n if (document.visibilityState === \"visible\") {\n // Clear any existing timeout before scheduling a new one\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n timeoutRef.current = setTimeout(() => {\n // Wrap async callback to catch unhandled rejections\n Promise.resolve(onVisible()).catch((error) => {\n console.error(\"Error in visibility check callback:\", error instanceof Error ? error.message : \"Unknown error\");\n });\n }, delay);\n }\n };\n\n document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n\n return () => {\n document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n // Clear pending timeout on cleanup\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n };\n }, [enabled, onVisible, delay]);\n}\n","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type PropsWithChildren,\n} from \"react\";\n\nimport type { IETHProvider } from \"@/core/types\";\nimport { useChainConnector } from \"@/hooks/useChainConnector\";\nimport { useVisibilityCheck } from \"@/hooks/useVisibilityCheck\";\nimport { useWalletConnect } from \"@/hooks/useWalletConnect\";\n\nexport interface ETHWalletLifecycleCallbacks {\n onConnect?: (address: string) => void | Promise<void>;\n onDisconnect?: () => void | Promise<void>;\n onAddressChange?: (newAddress: string) => void | Promise<void>;\n onError?: (error: Error, context?: { address?: string }) => void;\n}\n\ninterface ETHWalletContextType {\n loading: boolean;\n connected: boolean;\n address: string | undefined;\n disconnect: () => void;\n open: () => void;\n}\n\nconst ETHWalletContext = createContext<ETHWalletContextType>({\n loading: true,\n connected: false,\n address: undefined,\n disconnect: () => {},\n open: () => {},\n});\n\nexport interface ETHWalletProviderProps extends PropsWithChildren {\n callbacks?: ETHWalletLifecycleCallbacks;\n}\n\nexport const ETHWalletProvider = ({ children, callbacks }: ETHWalletProviderProps) => {\n const [loading, setLoading] = useState(true);\n const [address, setAddress] = useState<string>();\n const [provider, setProvider] = useState<IETHProvider | null>(null);\n\n const { open, disconnect: disconnectWallet } = useWalletConnect();\n const ethConnector = useChainConnector(\"ETH\");\n\n const disconnectLocally = useCallback(async () => {\n try {\n await ethConnector?.disconnect(\"local\");\n } catch (error) {\n console.error(\"Failed to disconnect ETH connector:\", error instanceof Error ? error.message : \"Unknown error\");\n }\n }, [ethConnector]);\n\n const connectETH = useCallback(\n async (walletAddress: string) => {\n try {\n setAddress(walletAddress);\n setLoading(false);\n\n await callbacks?.onConnect?.(walletAddress);\n } catch (error: unknown) {\n setLoading(false);\n callbacks?.onError?.(error instanceof Error ? error : new Error(\"ETH connection failed\"), {\n address: walletAddress,\n });\n }\n },\n [callbacks],\n );\n\n // Check for existing connection on mount (handles auto-reconnection)\n useEffect(() => {\n setLoading(false);\n if (!ethConnector) return;\n\n const checkExistingConnection = async () => {\n try {\n // First check if connector already has a connected wallet\n if (ethConnector.connectedWallet?.provider && !address) {\n const walletProvider = ethConnector.connectedWallet.provider;\n const addr = await walletProvider.getAddress();\n if (addr) {\n setProvider(walletProvider);\n connectETH(addr);\n }\n return;\n }\n\n // If not, try to auto-reconnect using the first available wallet\n // The AppKitProvider will detect existing wagmi connection and return immediately\n if (!address && ethConnector.wallets.length > 0) {\n const wallet = ethConnector.wallets[0]; // AppKit wallet\n if (wallet.provider) {\n try {\n // This will check for existing connection and return immediately if found\n const addr = await wallet.provider.getAddress();\n if (addr) {\n // Found existing connection, trigger manual connect to sync state\n await ethConnector.connect(wallet);\n }\n } catch (error) {\n // No existing connection, which is fine\n }\n }\n }\n } catch (error) {\n // No existing connection, which is fine\n }\n };\n\n checkExistingConnection();\n\n const unsubscribe = ethConnector.on(\"connect\", async (wallet) => {\n if (wallet.provider) {\n try {\n const addr = await wallet.provider.getAddress();\n if (addr) {\n setProvider(wallet.provider);\n connectETH(addr);\n }\n } catch (error) {\n console.error(\"Error getting ETH address:\", error instanceof Error ? error.message : \"Unknown error\");\n }\n }\n });\n\n // Restore connector state when wagmi restores the account after mount.\n // The existing wagmi connection keeps this call from opening the modal.\n const bootstrapWallet = ethConnector.wallets[0];\n const bootstrapProvider = bootstrapWallet?.provider;\n // Block duplicate events until React receives the restored address.\n let lateReconnectInFlight = false;\n const onLateReconnect = (accounts?: string[]) => {\n if (!accounts?.[0] || address || lateReconnectInFlight) return;\n lateReconnectInFlight = true;\n void ethConnector\n .connect(bootstrapWallet)\n .then((wallet) => {\n // A failed connection resolves null. Let the next event try again.\n if (!wallet) lateReconnectInFlight = false;\n })\n .catch((error) => {\n // Also allow a retry after an unexpected error.\n lateReconnectInFlight = false;\n console.error(\"ETH late reconnect failed:\", error instanceof Error ? error.message : \"Unknown error\");\n });\n };\n if (bootstrapProvider && typeof bootstrapProvider.on === \"function\") {\n bootstrapProvider.on(\"accountsChanged\", onLateReconnect);\n }\n\n return () => {\n unsubscribe();\n if (bootstrapProvider && typeof bootstrapProvider.off === \"function\") {\n bootstrapProvider.off(\"accountsChanged\", onLateReconnect);\n }\n };\n }, [ethConnector, connectETH, address]);\n\n useEffect(() => {\n if (!ethConnector) return;\n\n return ethConnector.on(\"disconnect\", async () => {\n setAddress(undefined);\n setProvider(null);\n try {\n await callbacks?.onDisconnect?.();\n } catch (error) {\n console.error(\"Error in onDisconnect callback:\", error instanceof Error ? error.message : \"Unknown error\");\n }\n });\n }, [ethConnector, callbacks]);\n\n // Track previous address to detect changes\n const prevAddressRef = useRef<string | undefined>(undefined);\n // Guard against duplicate event processing from provider and window.ethereum\n const isProcessingChangeRef = useRef(false);\n\n // Keep the ref in sync with React state\n useEffect(() => {\n prevAddressRef.current = address;\n }, [address]);\n\n // Listen for ETH account changes on the provider\n // Using provider state ensures React properly tracks when provider becomes available\n useEffect(() => {\n if (!provider) return;\n\n const onAccountsChanged = async (accounts: string[]) => {\n // Prevent duplicate processing if both provider and window.ethereum fire events\n if (isProcessingChangeRef.current) return;\n\n const newAddress = accounts[0];\n const previousAddress = prevAddressRef.current;\n\n if (newAddress && newAddress.toLowerCase() !== previousAddress?.toLowerCase()) {\n // Account changed - set guard before async operations\n isProcessingChangeRef.current = true;\n prevAddressRef.current = newAddress;\n setAddress(newAddress);\n try {\n await callbacks?.onAddressChange?.(newAddress);\n } catch (error: unknown) {\n callbacks?.onError?.(error instanceof Error ? error : new Error(\"ETH address change failed\"), {\n address: newAddress,\n });\n } finally {\n isProcessingChangeRef.current = false;\n }\n } else if (!newAddress && previousAddress) {\n disconnectLocally();\n }\n };\n\n if (typeof provider.on === \"function\") {\n provider.on(\"accountsChanged\", onAccountsChanged);\n }\n\n return () => {\n if (typeof provider.off === \"function\") {\n provider.off(\"accountsChanged\", onAccountsChanged);\n }\n };\n }, [provider, callbacks, disconnectLocally]);\n\n // Use only the active provider. window.ethereum can report unrelated accounts.\n\n // Check for wallet changes when the user returns to the tab.\n const checkETHConnection = useCallback(async () => {\n if (!provider) return;\n\n try {\n const currentAddress = await provider.getAddress();\n\n if (!currentAddress) {\n disconnectLocally();\n } else if (currentAddress.toLowerCase() !== address?.toLowerCase()) {\n // Account changed while tab was in background\n prevAddressRef.current = currentAddress;\n setAddress(currentAddress);\n await callbacks?.onAddressChange?.(currentAddress);\n }\n } catch (error) {\n console.error(\"ETH wallet connection check failed:\", error instanceof Error ? error.message : \"Unknown error\");\n disconnectLocally();\n }\n }, [provider, address, callbacks, disconnectLocally]);\n\n useVisibilityCheck(checkETHConnection, {\n enabled: Boolean(provider && address),\n });\n\n const connected = useMemo(() => Boolean(address), [address]);\n\n return (\n <ETHWalletContext.Provider\n value={{\n loading,\n connected,\n address,\n disconnect: () => disconnectWallet(\"ETH\"),\n open,\n }}\n >\n {children}\n </ETHWalletContext.Provider>\n );\n};\n\nexport const useETHWallet = () => useContext(ETHWalletContext);\n"],"names":["getDefaultExportFromCjs","x","browser","process","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","runClearTimeout","marker","queue","draining","currentQueue","queueIndex","cleanUpNextTick","drainQueue","timeout","len","args","i","Item","array","noop","name","dir","browserExports","process$1","ACCOUNT_CHANGE_EVENTS","isAccountChangeEvent","eventName","NETWORK_CHANGE_EVENT","DISCONNECT_EVENT","trackProviderIdentityChanges","provider","callback","event","_a","WALLET_MODAL_OPEN_EVENT","COSMOS_KEYSTORE_CHANGE_EVENTS","removeProviderListener","ONE_HOUR","Wallet","id","origin","icon","iconBackground","docs","networks","label","hardware","__publicField","onProgress","address","publicKeyHex","createNanoEvents","callbacks","length","cb","ERROR_CODES","WalletError","code","message","wallet","version","chainId","options","isUserRejectionMessage","lower","isSharedSessionRefusal","error","WalletConnector","wallets","config","selectedWallet","w","reportProgress","description","e","scope","generation","handler","Network","defaultWalletGetter","key","context","createWallet","metadata","walletGetter","nameGetter","iconGetter","createProvider","getWallet","createExternalWallet","createWalletConnector","persistent","accountStorage","disabledWallets","connectedWalletId","walletMetadata","injectableWallet","filteredWallets","connector","selectRedetectReconnectTargets","connectors","storage","allowReconnect","eligibleChainIds","targets","storedWalletId","UNISAT_READY_EVENT","FALLBACK_MS","useWalletRedetection","setConnectors","connectorsRef","useRef","connectorsBuilt","useEffect","inFlight","cancelled","reconnecting","pendingRestore","redetect","runRedetection","stale","c","swapIn","rebuilt","cc","appeared","before","wasInstalled","current","prev","next","inState","reconnectTargets","walletId","redetectColdStart","redetectInteractive","timer","hasWindow","usePersistState","initialState","getDefaultState","defaultValue","persistValue","state","setState","useState","Context","createContext","InscriptionProvider","children","lockInscriptions","toggleLockInscriptions","inscriptionContext","useMemo","useInscriptionProvider","useContext","WALLET_CONFIRMATION_RECEIPT_KEY","RECEIPT_VERSION","IDENTITY_CHANGE_EVENTS","connectorFor","chain","networkIdentity","value","sameIdentity","left","right","isReceiptEntry","entry","parseConfirmationReceipt","serialized","receipt","createConfirmationReceipt","connections","entries","connection","isValidConfirmationReceipt","requiredChainIds","account","candidate","isConfirmationReceiptCovered","isLiveConfirmationReceiptValid","network","_b","subscribeToConfirmationIdentityChanges","onChange","subscriptions","_c","accounts","approved","confirmedChains","defaultState","StateContext","filterWalletsByValidChains","selectedWallets","validChainIds","acc","StateProvider","chains","requirementsExpanded","renderedState","requiredChainIdsRef","useInsertionEffect","newChains","actions","params","required","confirmationReceipt","keepReceipt","ChainProvider","onError","requiredChains","init","useCallback","connectorPromises","chainMetadata","active","bump","unsubscribe","fn","supportedChains","jsx","useChainProviders","LifeCycleHooksProvider","useLifeCycleHooks","CONNECTED_ACCOUNTS_KEY","scopeKey","networkMap","readAccountsMap","raw","parsed","writeAccountsMap","map","createAccountStorage","ttl","getTimestamps","timestamps","isExpired","scoped","ts","now","deleted","MONOCHROME_MARK_BACKGROUND","ONEKEY_BRAND_GREEN","okxLogo","APPKIT_OPEN_EVENT","APPKIT_ETH_CONNECTOR_ID","APPKIT_BTC_CONNECTOR_ID","BIGINT_FINGERPRINT_TYPE","FUNCTION_FINGERPRINT_TYPE","CONFIG_FINGERPRINT_SERIALIZATION_ERROR","INITIAL_CONFIG_FUNCTION_ID","configFunctionIds","nextConfigFunctionId","getConfigFunctionId","existingId","createConfigFingerprint","fingerprint","_key","nestedValue","createAppKitCapabilities","projectId","ethChain","btcNetwork","appKitState","manualAppKitModal","manualAppKitCapabilities","failInitialization","getAppKitState","getAppKitModal","registerManualAppKitConfig","capability","modal","validateAppKitInitialization","setAppKitState","assertAppKitCapabilities","existing","requested","ETHEREUM_CAPABILITY","SHARED_WAGMI_REPLACEMENT_WARNING","sharedWagmiConfig","setSharedWagmiConfig","getSharedWagmiConfig","initializedState","hasSharedWagmiConfig","ethDisconnectWouldDropBitcoin","MODAL_CLOSE_CANCEL_GRACE_MS","WALLET_NOT_CONNECTED_ERROR_MESSAGE","ETH_FALLBACK_PROVIDER_NAME","ETH_FALLBACK_PROVIDER_ICON","AppKitProvider","initialAccount","getAccount","unwatchAccount","watchAccount","previousAddress","unwatchChain","watchChainId","previousChainId","data","handlers","currentAccount","resolve","reject","modalHasOpened","pendingCancellation","cleanup","unwatch","unsubscribeModal","latestAccount","wcConnector","walletConnect","result","connect","wagmiDisconnect","wagmiSignMessage","typedData","wagmiSignTypedData","tx","wagmiSendTransaction","parseEther","wagmiEstimateGas","wagmiSwitchChain","wagmiGetBalance","getTransactionCount","walletInfo","WALLET_PROVIDER_NAME","_wallet","appkit","createETHWagmiAdapter","ethRpcUrl","WagmiAdapter","createStorage","cookieStorage","baseAccount","http","initializeAppKitModal","capabilities","existingState","reownAppKitModal","wagmiAdapter","createAppKit","useAppKitOpenListener","handleOpenRequest","useChainConnector","FIRST_PARTY_ICONS","resolveFirstPartyIcon","walletName","match","useWidgetState","resolveEthDisplayWallet","firstParty","TERMINAL_CONNECT_ERROR_CODES","useWalletConnectors","btcValidation","confirmed","visible","selectWallet","removeWallet","displayLoader","displayChains","displayError","confirm","unconfirm","verifyBTCAddress","validationGenerationRef","previousRequiredChainIdsRef","confirmationCandidate","confirmationCandidateRef","dirtyOptionalChainsRef","requiredConnectorsReady","droppingRef","dropRejectedWallet","unsubscribeArr","connectorArr","connectedWallet","goToNextScreen","_d","useLayoutEffect","validateConfirmation","covered","previousCandidate","newlyRequiredChainIds","stopWatchingIdentity","useWalletWidgets","createChainWidget","externalConnectors","Fragment","Component","useWalletConnect","chainMap","openModal","displayWallets","reset","open","disconnect","selected","ChainButton","className","alt","logo","title","onClick","avatar","Avatar","getTestId","jsxs","Text","twMerge","ADDRESS_TRUNCATE_THRESHOLD","ADDRESS_EDGE_CHARS","truncateAddress","ConnectedWallet","memo","logoBackground","isCopied","copyToClipboard","useCopy","copied","handleCopy","WalletIcon","CheckIcon","CopyIcon","DISABLED_CONNECT_BG","SELECT_WALLET_TITLE_PREFIX","SELECT_WALLET_TITLE_SUFFIX","OPTIONAL_CHAIN_TITLE_SUFFIX","Chains","disabled","onConfirm","onSelectChain","Heading","optional","Button","openAppKitModal","ChainsContainer","props","chainArr","handleSelectChain","appkitId","connected","DEFAULT_ICON","Error","cancelButton","submitButton","onCancel","onSubmit","DialogBody","DialogFooter","ErrorContainer","screen","LoaderScreen","Loader","INSTALLED_ACCENT","INSTALLED_DOT","HARDWARE_ACCENT","HARDWARE_DOT","WalletButton","fallbackLink","installed","btnProps","normalizedName","Chip","TAPROOT_ADDRESS_PREFIX","BTC_TESTNET_FAUCET_URL","walletDisplayRank","Wallets","append","onSelectWallet","a","b","btcHint","prefix","handleWalletClick","WalletsContainer","widgets","currentChain","widget","SCREENS","Screen","CurrentScreen","WALLET_CHANGED_ERROR_MESSAGE","WALLET_NETWORK_MISSING_ERROR_MESSAGE","WALLET_NETWORK_MISMATCH_ERROR_MESSAGE","WALLET_PROVIDER_MISSING_ERROR_MESSAGE","findPrimaryConnection","collectConnections","copyConnections","accountCopy","walletCopy","hasSameIdentity","expected","identity","createConfirmationSnapshot","getConnectors","onOptionalError","candidates","verifiedCandidates","settledConnectors","settledConnections","stableCandidates","settled","identities","WalletDialog","closeButtonClassName","actionsClassName","close","acceptTermsOfService","walletWidgets","attemptGenerationRef","activeAttemptRef","activeIdentitySubscriptionRef","mountedRef","visibleRef","confirmedRef","confirmationInputsRef","invalidateAttempt","previous","requiredChainsChanged","index","handleClose","handleConfirm","isCurrentAttempt","confirmationHandoffPending","initialConnectors","initialReceipt","unsubscribeIdentity","watchingIdentity","confirmationSnapshot","uncovered","primary","checkIdentity","currentSnapshot","normalizedError","onBack","FullScreenDialog","useVisibilityCheck","onVisible","enabled","delay","timeoutRef","handleVisibilityChange","ETHWalletContext","ETHWalletProvider","loading","setLoading","setAddress","setProvider","disconnectWallet","ethConnector","disconnectLocally","connectETH","walletAddress","walletProvider","addr","bootstrapWallet","bootstrapProvider","lateReconnectInFlight","onLateReconnect","prevAddressRef","isProcessingChangeRef","onAccountsChanged","newAddress","checkETHConnection","currentAddress","useETHWallet"],"mappings":";;;;;;;;;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AAAA,IAAjB;AAAA,MACC,OAAO;AAAA,QACL,SAAAE;AAAA,QACA,WAAAxG;AAAA,QACA,SAAAtY;AAAA,QACA,YAAY,MAAMkf,EAAiB,KAAK;AAAA,QACxC,MAAA1J;AAAA,MAAA;AAAA,MAGD,UAAApP;AAAA,IAAA;AAAA,EAAA;AAGP,GAEa+Z,KAAe,MAAMzZ,GAAWkY,EAAgB;","x_google_ignoreList":[0,4]}
|
|
1
|
+
{"version":3,"file":"ETHWalletProvider-Dq5EwVtB.js","sources":["../../../node_modules/.pnpm/vite-plugin-node-polyfills@0.23.0_rollup@4.46.1_vite@6.4.1_@types+node@22.17.0_jiti@2.5_590787783d08c931a0b9f4ec9ff54180/node_modules/vite-plugin-node-polyfills/shims/process/dist/index.js","../src/constants/walletEvents.ts","../src/constants/index.ts","../src/core/Wallet.ts","../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js","../src/error/codes.ts","../src/error/index.ts","../src/core/WalletConnector.ts","../src/core/types.ts","../src/core/index.ts","../src/hooks/redetectReconnect.ts","../src/hooks/useWalletRedetection.ts","../src/hooks/usePersistState.ts","../src/context/Inscriptions.context.tsx","../src/core/confirmationReceipt.ts","../src/context/State.context.tsx","../src/context/Chain.context.tsx","../src/context/LifecycleHooks.context.tsx","../src/core/storage.ts","../src/core/wallets/constants.ts","../src/core/wallets/icons/okx.svg","../src/core/wallets/appkit/constants.ts","../src/core/wallets/appkit/state.ts","../src/core/wallets/eth/appkit/sharedConfig.ts","../src/core/wallets/eth/appkit/provider.ts","../src/core/wallets/eth/appkit/index.ts","../src/core/wallets/eth/icon.svg","../src/core/wallets/eth/index.ts","../src/core/wallets/eth/appkit/modal.ts","../src/hooks/appkit/useAppKitOpenListener.ts","../src/hooks/useChainConnector.ts","../src/core/wallets/firstPartyIcons.ts","../src/hooks/useWidgetState.ts","../src/hooks/useWalletConnectors.tsx","../src/hooks/useWalletWidgets.tsx","../src/hooks/useWalletConnect.ts","../src/components/ChainButton/index.tsx","../src/components/ConnectedWallet/index.tsx","../src/components/Chains/index.tsx","../src/components/Chains/container.tsx","../src/components/Error/index.tsx","../src/components/Error/container.tsx","../src/components/Loader/index.tsx","../src/components/WalletButton/index.tsx","../src/components/Wallets/index.tsx","../src/components/Wallets/container.tsx","../src/components/WalletProvider/components/Screen.tsx","../src/components/WalletProvider/components/WalletDialog.tsx","../src/hooks/useVisibilityCheck.ts","../src/providers/ETHWalletProvider.tsx"],"sourcesContent":["function getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar browser = {exports: {}};\n\n// shim for using process in browser\nvar process = browser.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ());\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] };\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\nvar browserExports = browser.exports;\nconst process$1 = /*@__PURE__*/getDefaultExportFromCjs(browserExports);\n\nexport { process$1 as default, process$1 as process };\n//# sourceMappingURL=index.js.map\n","/**\n * Wallet event name constants\n *\n * Different wallets use different event names for the same events.\n * These constants help normalize event handling across wallets.\n */\n\n/** Event names for account changes (different wallets use different names) */\nexport const ACCOUNT_CHANGE_EVENTS = [\"accountChanged\", \"accountsChanged\"] as const;\n\nexport type AccountChangeEvent = (typeof ACCOUNT_CHANGE_EVENTS)[number];\n\n/** Check if an event name is an account change event */\nexport function isAccountChangeEvent(eventName: string): eventName is AccountChangeEvent {\n return ACCOUNT_CHANGE_EVENTS.includes(eventName as AccountChangeEvent);\n}\n\nexport const NETWORK_CHANGE_EVENT = \"networkChanged\" as const;\n\n/** Event name for disconnect */\nexport const DISCONNECT_EVENT = \"disconnect\" as const;\n\nexport function trackProviderIdentityChanges(\n provider: { on?: (event: string, callback: () => void) => void },\n callback: () => void,\n): boolean {\n if (typeof provider.on !== \"function\") return false;\n\n try {\n provider.on(\"accountsChanged\", callback);\n } catch {\n return false;\n }\n\n [NETWORK_CHANGE_EVENT, DISCONNECT_EVENT].forEach((event) => {\n try {\n provider.on?.(event, callback);\n } catch {\n // Some wallet providers reject event names that they do not support.\n }\n });\n\n return true;\n}\n\n/**\n * Window event dispatched when the wallet-selection modal opens.\n *\n * Late-injection re-detection (`useWalletRedetection`) listens for this so a\n * wallet whose extension injected after the initial detection — and after the\n * fallback timeout — is still re-detected by the time the user actually opens\n * the modal, flipping it from a download link to a connect button.\n */\nexport const WALLET_MODAL_OPEN_EVENT = \"babylon-wallet#modal-open\" as const;\n\n/** Cosmos wallet keystore change events (different wallets use different window events) */\nexport const COSMOS_KEYSTORE_CHANGE_EVENTS = [\n \"keplr_keystorechange\",\n \"leap_keystorechange\",\n \"okx_keystorechange\",\n] as const;\n\n/**\n * Helper to remove event listener from a provider.\n * Falls back from removeListener to off for compatibility across wallet implementations.\n */\nexport function removeProviderListener(\n provider: { removeListener?: (event: string, cb: () => void) => void; off?: (event: string, cb: () => void) => void },\n event: string,\n callback: () => void,\n): void {\n if (typeof provider.removeListener === \"function\") {\n provider.removeListener(event, callback);\n } else if (typeof provider.off === \"function\") {\n provider.off(event, callback);\n }\n}\n","export * from \"./walletEvents\";\n\n/** Default account-storage lifetime. */\nexport const ONE_HOUR = 60 * 60 * 1000;\n","import type { Account, IProvider, IWallet, Network, ProgressReporter } from \"@/core/types\";\n\nexport interface WalletOptions<P extends IProvider> {\n id: string;\n name: string;\n icon: string;\n iconBackground?: string;\n docs: string;\n networks: Network[];\n origin: any;\n provider: P | null;\n label?: string;\n hardware?: boolean;\n}\n\nexport class Wallet<P extends IProvider> implements IWallet {\n readonly id: string;\n readonly origin: any;\n readonly name: string;\n readonly icon: string;\n readonly iconBackground?: string;\n readonly docs: string;\n readonly networks: Network[];\n readonly provider: P | null = null;\n readonly hardware: boolean;\n private readonly _label?: string;\n account: Account | null = null;\n\n constructor({ id, origin, name, icon, iconBackground, docs, networks, provider, label, hardware }: WalletOptions<P>) {\n this.id = id;\n this.origin = origin;\n this.name = name;\n this.icon = icon;\n this.iconBackground = iconBackground;\n this.docs = docs;\n this.networks = networks;\n this.provider = provider;\n this._label = label;\n this.hardware = hardware ?? false;\n }\n\n get installed() {\n return Boolean(this.provider);\n }\n\n get label() {\n return this._label ?? (this.installed ? \"Installed\" : \"\");\n }\n\n async connect(onProgress?: ProgressReporter) {\n if (!this.provider) {\n throw Error(\"Provider not found\");\n }\n\n await this.provider.connectWallet(onProgress);\n const [address, publicKeyHex] = await Promise.all([this.provider.getAddress(), this.provider.getPublicKeyHex()]);\n\n this.account = { address, publicKeyHex };\n\n return this;\n }\n\n clone() {\n return new Wallet({\n id: this.id,\n origin: this.origin,\n name: this.name,\n icon: this.icon,\n iconBackground: this.iconBackground,\n docs: this.docs,\n networks: this.networks,\n provider: this.provider,\n });\n }\n}\n","export let createNanoEvents = () => ({\n emit(event, ...args) {\n for (\n let callbacks = this.events[event] || [],\n i = 0,\n length = callbacks.length;\n i < length;\n i++\n ) {\n callbacks[i](...args)\n }\n },\n events: {},\n on(event, cb) {\n ;(this.events[event] ||= []).push(cb)\n return () => {\n this.events[event] = this.events[event]?.filter(i => cb !== i)\n }\n }\n})\n","export const ERROR_CODES = {\n // ===== General/Common Errors =====\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\", // Fallback\n INVALID_PARAMS: \"INVALID_PARAMS\", // Validation error\n CONNECTION_FAILED: \"CONNECTION_FAILED\", // Connection error\n METHOD_NOT_IMPLEMENTED: \"METHOD_NOT_IMPLEMENTED\", // Unimplemented feature\n MAX_ITERATION_EXCEEDED: \"MAX_ITERATION_EXCEEDED\", // Exceeded allowed iterations\n\n // ===== Wallet Extension/Provider =====\n EXTENSION_NOT_FOUND: \"EXTENSION_NOT_FOUND\", // Extension missing\n EXTENSION_CONTEXT_INVALIDATED: \"EXTENSION_CONTEXT_INVALIDATED\", // Context invalidated\n CONNECTION_REJECTED: \"CONNECTION_REJECTED\", // User rejected\n CONNECTION_CANCELED: \"CONNECTION_CANCELED\", // User canceled\n CHAIN_ID_NOT_INITIALIZED: \"CHAIN_ID_NOT_INITIALIZED\", // Chain ID missing\n RPC_URL_NOT_INITIALIZED: \"RPC_URL_NOT_INITIALIZED\", // RPC URL missing\n FAILED_TO_ADD_CHAIN: \"FAILED_TO_ADD_CHAIN\", // Add chain failed\n FAILED_TO_GET_KEY: \"FAILED_TO_GET_KEY\", // Key fetch failed\n WALLET_INITIALIZATION_FAILED: \"WALLET_INITIALIZATION_FAILED\", // Wallet initialization failed\n WALLET_NOT_CONNECTED: \"WALLET_NOT_CONNECTED\", // Not connected\n INCOMPATIBLE_WALLET_VERSION: \"INCOMPATIBLE_WALLET_VERSION\", // Version mismatch\n WALLET_METHOD_NOT_SUPPORTED: \"WALLET_METHOD_NOT_SUPPORTED\", // Wallet does not implement a required method\n NETWORK_NOT_ENABLED_IN_WALLET: \"NETWORK_NOT_ENABLED_IN_WALLET\", // Network not enabled\n WALLET_CONFIG_REQUIRED: \"WALLET_CONFIG_REQUIRED\", // Wallet configuration required\n SHARED_SESSION_DISCONNECT_REFUSED: \"SHARED_SESSION_DISCONNECT_REFUSED\", // Disconnecting one chain would also disconnect another\n\n // ===== Bitcoin/PSBT/Address =====\n INVALID_PUBLIC_KEY: \"INVALID_PUBLIC_KEY\", // Invalid public key\n ADDRESS_GENERATION_FAILED: \"ADDRESS_GENERATION_FAILED\", // Address generation failed\n UNSUPPORTED_NETWORK: \"UNSUPPORTED_NETWORK\", // Network unsupported\n INVALID_ADDRESS_PREFIX: \"INVALID_ADDRESS_PREFIX\", // Address prefix invalid\n MISSING_PSBT_HEX: \"MISSING_PSBT_HEX\", // PSBT hex missing\n PSBT_HEX_REQUIRED: \"PSBT_HEX_REQUIRED\", // PSBT hex required\n PSBTS_HEXES_REQUIRED: \"PSBTS_HEXES_REQUIRED\", // Multiple PSBT hexes required\n SIGNATURE_EXTRACT_ERROR: \"SIGNATURE_EXTRACT_ERROR\", // Signature extraction failed\n GENERATION_ERROR: \"GENERATION_ERROR\", // General generation error\n ADDRESS_NOT_FOUND: \"ADDRESS_NOT_FOUND\", // Address not found\n PUBLIC_KEY_NOT_FOUND: \"PUBLIC_KEY_NOT_FOUND\", // Public key not found\n EMPTY_WITNESS_STACK: \"EMPTY_WITNESS_STACK\", // Witness stack is empty\n\n // ===== QR/Hardware Wallet =====\n QR_READ_ERROR: \"QR_READ_ERROR\", // QR read failed\n QR_SCAN_ERROR: \"QR_SCAN_ERROR\", // QR scan failed\n DEVICE_CEREMONY_INVALID: \"DEVICE_CEREMONY_INVALID\", // Device ceremony state unusable — restart from derivation\n DEVICE_LOCKED: \"DEVICE_LOCKED\", // Hardware device is PIN-locked\n DEVICE_WRONG_APP: \"DEVICE_WRONG_APP\", // Wrong app open on the hardware device\n\n // ===== Inscriptions/Network =====\n INSCRIPTIONS_UNSUPPORTED_NETWORK: \"INSCRIPTIONS_UNSUPPORTED_NETWORK\", // Inscriptions unsupported\n INSCRIPTION_FETCH_ERROR: \"INSCRIPTION_FETCH_ERROR\", // Inscription fetch failed\n};\n","import { ERROR_CODES } from \"./codes\";\n\ninterface ErrorParams {\n code: string;\n message: string;\n wallet?: string;\n version?: string;\n chainId?: string;\n}\n\nexport class WalletError extends Error {\n readonly code: string;\n readonly wallet?: string;\n readonly version?: string;\n readonly chainId?: string;\n\n constructor({ code, message, wallet, version, chainId }: ErrorParams, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n this.wallet = wallet;\n this.version = version;\n this.chainId = chainId;\n }\n}\n\n/**\n * Returns true when the underlying error message indicates the user rejected\n * a wallet prompt (sign, connect, approve). Wallet providers expose this in\n * varying phrasings — match the exact ones used by supported wallets, not\n * the bare word \"rejected\" (some validation errors include it too).\n */\nexport function isUserRejectionMessage(message: string | undefined): boolean {\n if (!message) return false;\n const lower = message.toLowerCase();\n return (\n lower.includes(\"user rejected\") ||\n lower.includes(\"user denied\") ||\n lower.includes(\"user cancelled\") ||\n lower.includes(\"user canceled\")\n );\n}\n\n/**\n * Returns true when a provider refused a chain-scoped disconnect because that\n * chain shares its wallet session with another chain. The refusal is a\n * designed answer, not a fault: nothing was disconnected.\n */\nexport function isSharedSessionRefusal(error: unknown): error is WalletError {\n return error instanceof WalletError && error.code === ERROR_CODES.SHARED_SESSION_DISCONNECT_REFUSED;\n}\n\nexport * from \"./codes\";\n","import { createNanoEvents } from \"nanoevents\";\n\nimport { Wallet } from \"@/core/Wallet\";\nimport type { DisconnectScope, IConnector, IProvider } from \"@/core/types\";\nimport { ERROR_CODES, WalletError, isSharedSessionRefusal } from \"@/error\";\n\ntype DisconnectableProvider = IProvider & { disconnect?: (scope: DisconnectScope) => Promise<void> };\n\nexport interface ConnectorEvents<P extends IProvider> {\n connecting: (message?: string, description?: string) => void;\n connect: (wallet: Wallet<P>) => void;\n disconnect: (wallet: Wallet<P>) => void;\n error: (error: Error) => void;\n}\n\nexport class WalletConnector<N extends string, P extends IProvider, C> implements IConnector<N, P, C> {\n private _connectedWallet: Wallet<P> | null = null;\n private _connectionGeneration = 0;\n private _ee = createNanoEvents<ConnectorEvents<P>>();\n\n constructor(\n public readonly id: N,\n public readonly name: string,\n public readonly icon: string,\n public readonly wallets: Wallet<P>[],\n public readonly config: C,\n ) {}\n\n get connectedWallet() {\n return this._connectedWallet;\n }\n\n async connect(wallet: string | Wallet<P>) {\n try {\n const selectedWallet = typeof wallet === \"string\" ? this.wallets.find((w) => w.id === wallet) : wallet;\n\n if (!selectedWallet) {\n throw new WalletError({\n code: ERROR_CODES.EXTENSION_NOT_FOUND,\n message: \"Wallet not found\",\n });\n }\n this._ee.emit(\"connecting\", `Connecting ${selectedWallet.name}`);\n\n const reportProgress = (message?: string, description?: string) =>\n this._ee.emit(\"connecting\", message, description);\n await selectedWallet.connect(reportProgress);\n this._connectedWallet = selectedWallet;\n this._connectionGeneration += 1;\n this._ee.emit(\"connect\", this._connectedWallet);\n\n return this.connectedWallet;\n } catch (e: any) {\n this._ee.emit(\"error\", e);\n return null;\n }\n }\n\n async disconnect(scope: DisconnectScope = \"chain\") {\n const wallet = this._connectedWallet;\n const generation = this._connectionGeneration;\n if (!wallet) return;\n\n const provider = wallet.provider as DisconnectableProvider | null;\n if (provider?.disconnect) {\n try {\n await provider.disconnect(scope);\n } catch (error) {\n if (scope === \"chain\" && isSharedSessionRefusal(error)) throw error;\n this._ee.emit(\"error\", error instanceof Error ? error : new Error(String(error)));\n if (scope === \"chain\") throw error;\n }\n }\n if (this._connectedWallet !== wallet || this._connectionGeneration !== generation) return;\n this._connectedWallet = null;\n this._ee.emit(\"disconnect\", wallet);\n }\n\n clone() {\n return new WalletConnector(this.id, this.name, this.icon, this.wallets, this.config);\n }\n\n on<K extends keyof ConnectorEvents<P>>(name: K, handler: ConnectorEvents<P>[K]) {\n return this._ee.on(name, handler);\n }\n}\n","import { ChainInfo, OfflineAminoSigner, OfflineDirectSigner } from \"@keplr-wallet/types\";\nimport { ComponentType } from \"react\";\n\nexport type Fees = {\n // fee for inclusion in the next block\n fastestFee: number;\n // fee for inclusion in a block in 30 mins\n halfHourFee: number;\n // fee for inclusion in a block in 1 hour\n hourFee: number;\n // economy fee: inclusion not guaranteed\n economyFee: number;\n // minimum fee: the minimum fee of the network\n minimumFee: number;\n};\n\n// UTXO is a structure defining attributes for a UTXO\nexport interface UTXO {\n // hash of transaction that holds the UTXO\n txid: string;\n // index of the output in the transaction\n vout: number;\n // amount of satoshis the UTXO holds\n value: number;\n // the script that the UTXO contains\n scriptPubKey: string;\n}\n\nexport interface InscriptionIdentifier {\n // hash of transaction that holds the ordinals/brc-2-/runes etc in the UTXO\n txid: string;\n // index of the output in the transaction\n vout: number;\n}\n// supported networks\nexport enum Network {\n MAINNET = \"mainnet\",\n TESTNET = \"testnet\",\n SIGNET = \"signet\",\n}\n\n// WalletInfo is a structure defining attributes for a wallet\nexport type WalletInfo = {\n publicKeyHex: string;\n address: string;\n};\n\nexport interface BTCConfig {\n coinName: string;\n coinSymbol: string;\n networkName: string;\n mempoolApiUrl: string;\n network: Network;\n}\n\nexport type BBNConfig = {\n chainId: string;\n rpc: string;\n chainData: ChainInfo;\n networkName: string;\n networkFullName: string;\n coinSymbol: string;\n};\n\nexport interface ETHConfig {\n chainId: number;\n chainName: string;\n rpcUrl: string;\n explorerUrl: string;\n nativeCurrency: {\n name: string;\n symbol: string;\n decimals: number;\n };\n}\n\n// Ethereum specific types\nexport interface ETHTransactionRequest {\n to: string;\n value?: string;\n data?: string;\n gasLimit?: bigint;\n maxFeePerGas?: bigint;\n maxPriorityFeePerGas?: bigint;\n nonce?: number;\n}\n\nexport interface ETHTypedData {\n domain: {\n name?: string;\n version?: string;\n chainId?: number;\n verifyingContract?: string;\n salt?: string;\n };\n types: Record<string, Array<{ name: string; type: string }>>;\n primaryType: string;\n message: Record<string, any>;\n}\n\nexport interface NetworkInfo {\n name: string;\n chainId: string;\n}\n\nexport interface IETHProvider extends IProvider {\n /**\n * Signs a human-readable message using personal_sign\n * @param message - The message to sign\n * @returns A promise that resolves to the signature\n */\n signMessage(message: string): Promise<string>;\n\n /**\n * Signs structured data using eth_signTypedData_v4 (EIP-712)\n * @param typedData - The structured data to sign\n * @returns A promise that resolves to the signature\n */\n signTypedData(typedData: ETHTypedData): Promise<string>;\n\n /**\n * Sends a transaction to the blockchain\n * @param tx - The transaction request\n * @returns A promise that resolves to the transaction hash\n */\n sendTransaction(tx: ETHTransactionRequest): Promise<string>;\n\n /**\n * Estimates gas for a transaction\n * @param tx - The transaction request\n * @returns A promise that resolves to the estimated gas\n */\n estimateGas(tx: ETHTransactionRequest): Promise<bigint>;\n\n /**\n * Gets the current chain ID\n * @returns A promise that resolves to the chain ID\n */\n getChainId(): Promise<number>;\n\n /**\n * Switches to a different chain\n * @param chainId - The chain ID to switch to\n * @returns A promise that resolves when the switch is complete\n */\n switchChain(chainId: number): Promise<void>;\n\n /**\n * Gets the account balance\n * @returns A promise that resolves to the balance in wei\n */\n getBalance(): Promise<bigint>;\n\n /**\n * Gets the account nonce\n * @returns A promise that resolves to the nonce\n */\n getNonce(): Promise<number>;\n\n /**\n * Gets network information\n * @returns A promise that resolves to network info\n */\n getNetworkInfo(): Promise<NetworkInfo>;\n\n /**\n * Gets the wallet provider name\n * @returns The name of the wallet provider\n */\n getWalletProviderName(): string;\n\n /**\n * Gets the wallet provider icon\n * @returns The icon of the wallet provider\n */\n getWalletProviderIcon(): string;\n\n /**\n * Registers an event listener for the specified event\n * @param eventName - The name of the event to listen for\n * @param handler - The callback function to be executed when the event occurs\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n on(eventName: string, handler: Function): void;\n\n /**\n * Unregisters an event listener for the specified event\n * @param eventName - The name of the event to listen for\n * @param handler - The callback function to be executed when the event occurs\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n off(eventName: string, handler: Function): void;\n}\n\nexport type ProgressReporter = (message?: string, description?: string) => void;\n\nexport interface IProvider {\n connectWallet: (onProgress?: ProgressReporter) => Promise<void>;\n getAddress: () => Promise<string>;\n getPublicKeyHex: () => Promise<string>;\n isIdentityCurrent?: () => boolean;\n}\n\nexport interface IWallet<P extends IProvider = IProvider> {\n id: string;\n name: string;\n icon: string;\n // Solid brand-color fill shown behind `icon` in the wallet-select list, where\n // the icon is clipped to a rounded square rather than shown as a raw circle\n // (see WalletButton). Undefined falls back to no fill (transparent corners).\n iconBackground?: string;\n docs: string;\n installed: boolean;\n provider: P | null;\n account: Account | null;\n label: string;\n // Explicit hardware-wallet marker. Drives the \"available\" badge and the\n // connect-list ordering. Do NOT infer this from `label`: software wallets\n // (injectable, AppKit) carry labels too, so label truthiness is not a\n // hardware signal.\n hardware?: boolean;\n}\n\n/** Every chain the connector can build a wallet connector for. */\nexport type ChainId = \"BTC\" | \"BBN\" | \"ETH\";\n\n/**\n * `\"chain\"` asks the provider to disconnect only this connector's chain; the\n * provider refuses with `SHARED_SESSION_DISCONNECT_REFUSED` when that would\n * also disconnect another chain. `\"all\"` is an explicit disconnect-everything\n * request and is never refused. `\"local\"` drops this connector's wallet and\n * the provider's cached session without any remote call: for a wallet the app\n * rejected after connecting, or one the provider's backend already reports\n * disconnected. It is never refused.\n */\nexport type DisconnectScope = \"chain\" | \"all\" | \"local\";\n\nexport interface IChain<K extends string = string, P extends IProvider = IProvider, C = any> {\n id: K;\n name: string;\n icon: string;\n wallets: IWallet<P>[];\n config: C;\n}\n\nexport interface IConnector<K extends string = string, P extends IProvider = IProvider, C = any>\n extends IChain<K, P, C> {\n connect(wallet: string | IWallet<P>): Promise<IWallet<P> | null>;\n /**\n * Rejects only for `\"chain\"`: with `SHARED_SESSION_DISCONNECT_REFUSED` when\n * the provider refused, or with the provider's error when the remote\n * disconnect failed. Either way nothing was disconnected, so the wallet\n * stays connected and no `disconnect` event fires; only a genuine failure\n * is also reported on `error`. `\"all\"` and `\"local\"` always finish the\n * local teardown and report a provider failure on `error`.\n */\n disconnect(scope?: DisconnectScope): Promise<void>;\n on(event: string, cb: (wallet: IWallet<P>) => void): () => void;\n}\n\nexport interface Account {\n address: string;\n publicKeyHex: string;\n}\n\nexport interface WalletMetadata<P extends IProvider, C> {\n id: string;\n wallet?: string | ((context: any, config: C) => any);\n label?: string;\n // Marks the entry as a hardware wallet so the UI shows the \"available\" badge\n // and groups it after installed software wallets. Set explicitly per wallet.\n hardware?: boolean;\n name: string | ((wallet: any, config: C) => Promise<string>);\n icon: string | ((wallet: any, config: C) => Promise<string>);\n // See `IWallet.iconBackground`.\n iconBackground?: string;\n docs: string;\n networks: Network[];\n createProvider: (wallet: any, config: C) => P;\n}\n\nexport interface ChainMetadata<N extends string, P extends IProvider, C> {\n chain: N;\n name: string;\n icon: string;\n wallets: WalletMetadata<P, C>[];\n}\n\nexport interface ExternalWalletProps<P extends IProvider> {\n id: string;\n name: string;\n icon: string;\n provider: P;\n}\nexport interface WalletConnectorProps<N extends string, P extends IProvider, C> {\n persistent: boolean;\n metadata: ChainMetadata<N, P, C>;\n context: any;\n config: C;\n accountStorage: HashMap;\n disabledWallets?: string[];\n}\n\nexport interface WalletProps<P extends IProvider, C> {\n metadata: WalletMetadata<P, C>;\n context: any;\n config: C;\n}\n\nexport interface WidgetProps<P extends IProvider = IProvider> {\n id: string;\n connector: IConnector;\n createWallet: (props: ExternalWalletProps<P>) => IWallet<P>;\n onError?: (e: Error) => void;\n}\n\nexport type WidgetComponent<P extends IProvider = IProvider> = ComponentType<WidgetProps<P>>;\n\nexport interface ExternalConnector<P extends IProvider = IProvider> {\n id: string;\n widget: WidgetComponent<P>;\n}\n\nexport interface Contract {\n id: string;\n params: Record<string, string | number | string[] | number[]>;\n}\n\nexport interface Action {\n name: string;\n}\n\n/**\n * Options for signing a specific input in a PSBT.\n */\nexport interface SignInputOptions {\n /** Input index to sign */\n index: number;\n /** Address for signing (optional) */\n address?: string;\n /** Public key for signing (optional, hex string) */\n publicKey?: string;\n /** Sighash types (optional) */\n sighashTypes?: number[];\n /**\n * Whether the wallet should sign with the tweaked (key-path) signer.\n * Set `false` for Taproot script-path spends, where signing uses the\n * untweaked internal key. If omitted, the wallet's default behavior\n * applies.\n */\n useTweakedSigner?: boolean;\n /**\n * @deprecated Use `useTweakedSigner` instead. `disableTweakSigner: true`\n * is equivalent to `useTweakedSigner: false`; `useTweakedSigner` takes\n * precedence when both are set.\n *\n * `useTweakedSigner` is the canonical field used by UniSat and newer OKX\n * wallet versions. Migrating aligns our interface with the wallet-side\n * convention and avoids the historical divergence in OKX's\n * `disableTweakSigner` implementation.\n */\n disableTweakSigner?: boolean;\n}\n\nexport interface SignPsbtOptions {\n autoFinalized?: boolean;\n contracts?: Contract[];\n action?: Action;\n /**\n * Specific inputs to sign.\n * If not provided, wallet will attempt to sign all inputs it can.\n * Use this to restrict signing to specific inputs (e.g., only depositor's input in payout tx).\n */\n signInputs?: SignInputOptions[];\n /**\n * Human-readable label for the signing step (e.g. \"Transaction 3 of 12\").\n * Honored by wallets that render their own signing UI — Keystone shows it\n * above the QR code so the user can track progress through a batch. Wallets\n * that sign in their extension popup ignore it.\n */\n displayMessage?: string;\n}\n\n/** One committed device ceremony inside a `signPsbts` batch. Counts only — never payload. */\nexport interface SigningProgress {\n readonly completed: number;\n readonly total: number;\n}\n\nexport interface IBTCProvider extends IProvider {\n /**\n * Signs the given PSBT in hex format.\n * @param psbtHex - The hex string of the unsigned PSBT to sign.\n * @param options - Optional parameters for signing the PSBT.\n * @returns A promise that resolves to the hex string of the signed PSBT.\n */\n signPsbt(psbtHex: string, options?: SignPsbtOptions): Promise<string>;\n\n /**\n * Signs multiple PSBTs in hex format.\n * @param psbtsHexes - The hex strings of the unsigned PSBTs to sign.\n * @param options - Optional parameters for signing the PSBTs.\n * @returns A promise that resolves to an array of hex strings, each representing a signed PSBT.\n */\n signPsbts(psbtsHexes: string[], options?: SignPsbtOptions[]): Promise<string[]>;\n\n /**\n * Gets the network of the current account.\n * @returns A promise that resolves to the network of the current account.\n */\n getNetwork(): Promise<Network>;\n\n /**\n * Reads the wallet's live accounts WITHOUT prompting the user\n * (non-interactive). Implemented only by wallets where an empty result is a\n * reliable silent-lock signal: UniSat returns [] when the wallet is locked\n * while a stale cached `getAddress()` still reports the last-known address,\n * so it can be polled to detect a silent auto-lock that fires no event.\n * Unlike `connectWallet()` it never surfaces the unlock / connection popup.\n *\n * Intentionally omitted by OKX and OneKey: their `getAccounts()` returns the\n * cached / dApp-authorized address even when the keyring is locked, so an\n * empty-array read is not a lock signal there. Optional — callers MUST\n * feature-detect (`typeof provider.getAccounts === \"function\"`) and treat a\n * missing method as \"lock cannot be probed\", never as locked.\n * @returns A promise that resolves to the active account addresses.\n */\n getAccounts?(): Promise<string[]>;\n\n /**\n * Requests cancellation of the in-flight signing ceremony\n * (signPsbt/signPsbts/signMessage). A REQUEST, not a settle: the provider\n * aborts at its next device exchange boundary, and the sign promise rejects\n * with `CONNECTION_REJECTED` only then. No-op when nothing is in flight.\n *\n * Implemented only by hardware providers whose ceremonies block on a\n * physical device (currently the Ledger vault provider). Optional — callers\n * MUST feature-detect (`typeof provider.cancelSigning === \"function\"`) and\n * hide the cancel affordance when the method is missing.\n */\n cancelSigning?(): void;\n\n /**\n * Subscribes to per-PSBT progress inside `signPsbts`: fires after each\n * device ceremony commits, with `completed` = PSBT ceremonies committed\n * so far and `total` = the batch length. Never fires for `signPsbt`\n * or before the first ceremony. A ceremony that fails emits no tick, while\n * ticks for ceremonies that committed before a later rejection stand — the\n * promise settle is the terminal signal. Listeners run synchronously inside\n * the signing loop: a throw is swallowed, a returned promise is neither\n * awaited nor observed. Ticks carry no batch identity, so implementers MUST\n * reject an overlapping `signPsbts` rather than queue it. Returns the\n * unsubscribe. The subscription outlives a batch but not the session —\n * teardown (disconnect or dead-session cleanup) drops every listener, so\n * subscribe per sign call.\n *\n * Implemented only by hardware providers that run one device ceremony per\n * PSBT (currently the Ledger vault provider). Optional — callers MUST\n * feature-detect (`typeof provider.subscribeSigningProgress === \"function\"`)\n * and fall back to the batch settle when the method is missing.\n */\n subscribeSigningProgress?(listener: (progress: SigningProgress) => void): () => void;\n\n /**\n * Signs a message using either BIP322-Simple or ECDSA signing method.\n * @param message - The message to sign.\n * @param type - The signing method to use.\n * @returns A promise that resolves to the signed message.\n */\n signMessage(message: string, type: \"bip322-simple\" | \"ecdsa\"): Promise<string>;\n\n /**\n * Retrieves the inscriptions for the connected wallet.\n * @returns A promise that resolves to an array of inscriptions.\n */\n getInscriptions(): Promise<InscriptionIdentifier[]>;\n\n /**\n * Registers an event listener for the specified event.\n * At the moment, only the \"accountChanged\" event is supported.\n * @param eventName - The name of the event to listen for.\n * @param callBack - The callback function to be executed when the event occurs.\n */\n on(eventName: string, callBack: () => void): void;\n\n /**\n * Unregisters an event listener for the specified event.\n * @param eventName - The name of the event to listen for.\n * @param callBack - The callback function to be executed when the event occurs.\n */\n off(eventName: string, callBack: () => void): void;\n\n /**\n * Gets the name of the wallet provider.\n * @returns A promise that resolves to the name of the wallet provider.\n */\n getWalletProviderName(): Promise<string>;\n\n /**\n * Gets the icon of the wallet provider.\n * @returns A promise that resolves to the icon of the wallet provider.\n */\n getWalletProviderIcon(): Promise<string>;\n\n /**\n * Gets the version of the wallet provider.\n * @returns A promise that resolves to the version of the wallet provider.\n */\n getVersion?(): Promise<string>;\n\n /**\n * Derives a deterministic 32-byte value from the wallet's key material,\n * an application name, and an application-provided context string.\n *\n * Conforms to the `deriveContextHash` wallet API contract that the\n * ts-sdk conformance vectors pin\n * (`tbv/core/vault-secrets/__tests__/deriveContextHash.vectors.test.ts`).\n * Implementations\n * that do not support this method MUST throw a {@link WalletError}\n * with code {@link ERROR_CODES.WALLET_METHOD_NOT_SUPPORTED} so the\n * caller can branch deterministically on capability.\n *\n * The wallet itself enforces the contract's input/output validation\n * (`appName` charset and length, `context` even-length lowercase hex,\n * 64-char hex output). Adapters forward without re-validating.\n *\n * @param appName - Application identifier (1-64 bytes, `[a-z0-9\\-]`).\n * Displayed by the wallet in its approval dialog.\n * @param context - Application-specific context, hex-encoded\n * (even-length, lowercase, no `0x` prefix, non-empty,\n * ≤ 2048 hex chars / 1024 bytes).\n * @returns 64-char lowercase hex string (32 bytes).\n * @throws {@link WalletError} with code\n * {@link ERROR_CODES.WALLET_METHOD_NOT_SUPPORTED} when the wallet\n * does not implement the method.\n */\n deriveContextHash(appName: string, context: string): Promise<string>;\n}\n\nexport interface IBBNProvider extends IProvider {\n /**\n * Gets the name of the wallet provider.\n * @returns A promise that resolves to the name of the wallet provider.\n */\n getWalletProviderName(): Promise<string>;\n\n /**\n * Gets the icon of the wallet provider.\n * @returns A promise that resolves to the icon of the wallet provider.\n */\n getWalletProviderIcon(): Promise<string>;\n\n /**\n * Retrieves an offline signer that supports both Amino and Direct signing methods.\n * This signer is used for signing transactions offline before broadcasting them to the network.\n *\n * @returns {Promise<OfflineAminoSigner & OfflineDirectSigner>} A promise that resolves to a signer supporting both Amino and Direct signing\n * @throws {Error} If wallet connection is not established or signer cannot be retrieved\n */\n getOfflineSigner(): Promise<OfflineAminoSigner & OfflineDirectSigner>;\n\n /**\n * Retrieves an offline signer that supports either Amino or Direct signing methods.\n * This is required for compatibility with older wallets and hardware wallets (like Ledger) that do not support both signing methods.\n * This signer is used for signing transactions offline before broadcasting them to the network.\n *\n * @returns {Promise<OfflineAminoSigner & OfflineDirectSigner>} A promise that resolves to a signer supporting either Amino or Direct signing\n * @throws {Error} If wallet connection is not established or signer cannot be retrieved\n */\n getOfflineSignerAuto?(): Promise<OfflineAminoSigner | OfflineDirectSigner>;\n\n /**\n * Registers an event listener for the specified event.\n * At the moment, only the \"accountChanged\" event is supported.\n * @param eventName - The name of the event to listen for.\n * @param callBack - The callback function to be executed when the event occurs.\n */\n on(eventName: string, callBack: () => void): void;\n\n /**\n * Unregisters an event listener for the specified event.\n * @param eventName - The name of the event to listen for.\n * @param callBack - The callback function to be executed when the event occurs.\n */\n off(eventName: string, callBack: () => void): void;\n\n /**\n * Gets the version of the wallet provider.\n * @returns A promise that resolves to the version of the wallet provider.\n */\n getVersion?(): Promise<string>;\n}\n\nexport interface HashMap {\n get: (key: string) => string | undefined;\n set: (key: string, value: any) => void;\n has: (key: string) => boolean;\n delete: (key: string) => boolean;\n}\n","import { type WalletOptions, Wallet } from \"./Wallet\";\nimport { WalletConnector } from \"./WalletConnector\";\nimport { ExternalWalletProps, IProvider, Network, WalletConnectorProps, WalletProps } from \"./types\";\n\nconst defaultWalletGetter = (key: string) => (context: any) => context[key];\n\nexport const createWallet = async <P extends IProvider, C>({ metadata, context, config }: WalletProps<P, C>) => {\n const {\n id,\n wallet: walletGetter,\n name: nameGetter,\n icon: iconGetter,\n iconBackground,\n docs = \"\",\n networks = [],\n createProvider,\n label,\n hardware,\n } = metadata;\n\n const options: WalletOptions<P> = {\n id,\n name: \"\",\n icon: \"\",\n iconBackground,\n origin: null,\n provider: null,\n docs,\n networks,\n label,\n hardware,\n };\n\n if (walletGetter) {\n const getWallet = typeof walletGetter === \"string\" ? defaultWalletGetter(walletGetter) : walletGetter;\n\n options.origin = (await getWallet(context, config)) ?? null;\n options.provider = options.origin ? createProvider(options.origin, config) : null;\n } else {\n options.origin = null;\n options.provider = createProvider(null, config);\n }\n\n if (typeof nameGetter === \"string\") {\n options.name = nameGetter ?? \"\";\n } else {\n options.name = options.origin ? await nameGetter(options.origin, config) : \"\";\n }\n\n if (typeof iconGetter === \"string\") {\n options.icon = iconGetter ?? \"\";\n } else {\n options.icon = options.origin ? await iconGetter(options.origin, config) : \"\";\n }\n\n return new Wallet(options);\n};\n\nexport const createExternalWallet = <P extends IProvider>({ id, name, icon, provider }: ExternalWalletProps<P>) =>\n new Wallet({\n id,\n origin: null,\n name,\n icon,\n docs: \"\",\n networks: [Network.MAINNET, Network.SIGNET],\n provider,\n });\n\nexport const createWalletConnector = async <N extends string, P extends IProvider, C>({\n persistent,\n metadata,\n context,\n config,\n accountStorage,\n disabledWallets,\n}: WalletConnectorProps<N, P, C>): Promise<WalletConnector<N, P, C>> => {\n const wallets: Wallet<P>[] = [];\n const connectedWalletId = persistent ? accountStorage.get(metadata.chain) : undefined;\n\n for (const walletMetadata of metadata.wallets) {\n if (disabledWallets?.includes(walletMetadata.id)) {\n continue;\n }\n wallets.push(\n await createWallet({\n metadata: walletMetadata,\n context,\n config,\n }),\n );\n }\n const injectableWallet = wallets.find((w) => w.id === \"injectable\" && w.installed);\n const filteredWallets = wallets.filter(\n (w) => w.name.toLowerCase() !== injectableWallet?.name.toLowerCase() || w.id === \"injectable\",\n );\n const connector = new WalletConnector(metadata.chain, metadata.name, metadata.icon, filteredWallets, config);\n\n const shouldAutoReconnect =\n metadata.chain !== \"ETH\" &&\n connectedWalletId &&\n wallets.some((wallet) => wallet.id === connectedWalletId && wallet.installed);\n\n if (shouldAutoReconnect) {\n // Fire-and-forget: do NOT await the reconnect handshake. Awaiting it here\n // blocks `createWalletConnector`, and therefore `ChainProvider.init()`'s\n // `Promise.all` over every chain, on the BTC extension responding. A locked\n // or unresponsive wallet would otherwise hang init indefinitely and leave\n // the whole connection UI (BTC *and* ETH) stuck loading. The reconnect\n // result is delivered through the connector's `connect`/`error` events,\n // which `ChainProvider`, `BTCWalletProvider`, and `useWalletConnectors`\n // already subscribe to. `connector.connect` swallows its own errors, so the\n // extra catch is just defensive against an unexpected synchronous throw.\n void connector.connect(connectedWalletId).catch((error) => {\n console.error(\"Auto-reconnect failed:\", error instanceof Error ? error.message : \"Unknown error\");\n });\n }\n\n return connector;\n};\n","import type { HashMap, IProvider } from \"@/core/types\";\nimport type { WalletConnector } from \"@/core/WalletConnector\";\n\n/**\n * Decision (kept pure, and free of the SVG-importing wallet metadata, so it can\n * be unit-tested without React): which of the just-redetected connectors should\n * have their previously-stored session reconnected.\n *\n * A connector qualifies only when sessions are persisted, the trigger allows\n * reconnect (cold-start, not the interactive modal-open path — which must not\n * race a manual connect), its chain is **eligible** (it participated in a\n * late-injection redetection this session — see `eligibleChainIds` below),\n * storage still names a wallet for that chain, that wallet is now installed, and\n * the connector isn't already connected.\n *\n * `eligibleChainIds` is the key guard: only chains that actually late-injected\n * are eligible. ETH/AppKit never late-injects (it's always installed, so never\n * `stale`/`appeared`), so it's never eligible — which is what keeps this from\n * calling `ethConnector.connect()` and popping the AppKit modal on reload (core\n * excludes ETH from auto-reconnect for the same reason).\n */\nexport function selectRedetectReconnectTargets({\n connectors,\n storage,\n allowReconnect,\n persistent,\n eligibleChainIds,\n}: {\n connectors: WalletConnector<string, IProvider, any>[];\n storage: Pick<HashMap, \"get\">;\n allowReconnect: boolean;\n persistent: boolean;\n eligibleChainIds: Set<string>;\n}): { connector: WalletConnector<string, IProvider, any>; walletId: string }[] {\n if (!allowReconnect || !persistent) return [];\n\n const targets: { connector: WalletConnector<string, IProvider, any>; walletId: string }[] = [];\n for (const connector of connectors) {\n if (!eligibleChainIds.has(connector.id)) continue;\n if (connector.connectedWallet) continue;\n const storedWalletId = storage.get(connector.id);\n if (!storedWalletId) continue;\n if (!connector.wallets.some((w) => w.id === storedWalletId && w.installed)) continue;\n targets.push({ connector, walletId: storedWalletId });\n }\n return targets;\n}\n","import type { Dispatch, SetStateAction } from \"react\";\nimport { useEffect, useRef } from \"react\";\n\nimport { WALLET_MODAL_OPEN_EVENT } from \"@/constants/walletEvents\";\nimport { createWalletConnector } from \"@/core\";\nimport type { HashMap, IProvider } from \"@/core/types\";\nimport type { WalletConnector } from \"@/core/WalletConnector\";\nimport type { ChainConfigArr, ChainMetadataMap, Connectors } from \"@/context/Chain.context\";\n\nimport { selectRedetectReconnectTargets } from \"./redetectReconnect\";\n\n/** UniSat dispatches this on `window` once its provider is ready. */\nconst UNISAT_READY_EVENT = \"unisat#initialized\";\n\n/**\n * Fallback delay for the cold-start re-detection when no wallet emits a ready\n * event. Long enough to cover UniSat's phishing-detection await, short enough\n * that a genuinely-uninstalled wallet isn't shown as \"checking\" for long.\n */\nconst FALLBACK_MS = 3000;\n\ninterface UseWalletRedetectionParams {\n /** Current connector map from `ChainProvider` state. */\n connectors: Connectors;\n /** `ChainProvider`'s connector-state setter. */\n setConnectors: Dispatch<SetStateAction<Connectors>>;\n /** Per-chain config array — same one passed to `createWalletConnector`. */\n config: Readonly<ChainConfigArr>;\n /** Wallet-detection context — typically `window`. */\n context: any;\n /** Account storage used for connector construction. */\n storage: HashMap;\n /** Wallet ids to exclude from connector construction. */\n disabledWallets?: string[];\n /**\n * Whether sessions are persisted (same flag passed to `createWalletConnector`).\n * When true, a cold-start re-detection that re-installs a previously-stored\n * wallet auto-reconnects it (see the reconnect block below).\n */\n persistent: boolean;\n /** Chain metadata for the entry point in use — see `ChainMetadataMap`. */\n metadata: ChainMetadataMap;\n}\n\n/**\n * Late-injection re-detection.\n *\n * Browser wallet extensions inject their `window` provider asynchronously\n * (e.g. UniSat's content script awaits phishing-detection before defining\n * `window.unisat`), so the one-shot detection in `ChainProvider`'s `init()`\n * can run before the extension is ready and leave a genuinely-installed\n * wallet stuck at `installed: false` — the wallet modal then shows it as a\n * download link instead of a connect button.\n *\n * Once the connectors are built, this re-detects on whichever of these fires:\n * UniSat's `unisat#initialized` event, a short fallback timeout (covers\n * wallets that emit no ready event), or every time the wallet modal opens\n * (`WALLET_MODAL_OPEN_EVENT`) — the last one covers an extension that injects\n * later than the fallback, so it still flips to a connect button by the time\n * the user looks at the list. Same event-or-timeout approach wagmi and\n * MetaMask's `detect-provider` use for this race.\n *\n * Re-detection is idempotent and safe to run repeatedly: only not-yet-connected\n * chains with an undetected wallet are rebuilt (it bails immediately when there\n * are none), and the merge re-checks connection state, so a live connection is\n * never dropped. A single in-flight guard prevents overlapping passes (e.g. the\n * event and the timeout firing close together).\n *\n * The connector *rebuild* always passes `persistent: false` so it does no\n * auto-reconnect itself. Reconnect of a previously-stored session is then\n * done explicitly, and only for the **cold-start** triggers (`unisat#initialized`\n * and the fallback timeout) where the modal is closed and there is no manual\n * connect to race. The interactive `WALLET_MODAL_OPEN_EVENT` trigger stays\n * detect-only (`allowReconnect: false`) — the user is actively choosing a wallet\n * there, so auto-reconnecting could double-prompt. Without this, a session that\n * lost the cold-start detection race (extension injected after `init()`) would\n * stay disconnected even though storage still names the wallet — leaving e.g.\n * ETH reconnected while BTC/UniSat shows as \"Connect\".\n */\nexport function useWalletRedetection({\n connectors,\n setConnectors,\n config,\n context,\n storage,\n disabledWallets,\n persistent,\n metadata,\n}: UseWalletRedetectionParams): void {\n // Mirror the latest connectors into a ref so the effect reads current\n // state without depending on it (which would re-run it).\n const connectorsRef = useRef(connectors);\n connectorsRef.current = connectors;\n\n // True once `init()` has populated the connectors.\n const connectorsBuilt = Object.values(connectors).some(Boolean);\n\n useEffect(() => {\n // Arm only after `init()` has populated connectors — otherwise a fast\n // event/timeout could consume a re-detect against an empty set.\n if (!connectorsBuilt) return;\n\n let inFlight = false; // prevent overlapping passes (event vs. timeout vs. modal-open)\n let cancelled = false; // effect cleaned up\n // Chains with a stored-session reconnect already in flight, so the two\n // cold-start triggers (ready event + fallback timer) firing before it\n // settles don't fire duplicate `connect()`s. Persists across redetect calls\n // within this effect instance.\n const reconnecting = new Set<string>();\n // Chains that participated in late-injection redetection (their wallet\n // `appeared` after the one-shot init detection) and still need their stored\n // session restored. Only these are eligible for redetect reconnect — so\n // ETH/AppKit (never late-injects) and normally-detected wallets (init\n // auto-reconnect handles them) are excluded. Persists across passes so a\n // modal-open detect-only pass that swaps a wallet in is still restored by a\n // later cold-start pass.\n const pendingRestore = new Set<string>();\n\n // `allowReconnect` is true only for the non-interactive cold-start triggers\n // (see listeners below); the modal-open trigger passes false.\n const redetect = async (allowReconnect: boolean) => {\n if (inFlight || cancelled) return;\n inFlight = true;\n try {\n await runRedetection(allowReconnect);\n } finally {\n inFlight = false;\n }\n };\n\n const runRedetection = async (allowReconnect: boolean) => {\n // 1. Re-detect connectors whose wallet injected after the one-shot\n // detection in init() (e.g. UniSat) and swap the now-installed ones in.\n const stale = (\n Object.values(connectorsRef.current).filter(Boolean) as WalletConnector<string, IProvider, any>[]\n ).filter(\n (c) =>\n Boolean(metadata[c.id as keyof ChainMetadataMap]) &&\n !c.connectedWallet &&\n c.wallets.some((w) => w.id !== \"injectable\" && !w.installed),\n );\n\n let swapIn: WalletConnector<string, IProvider, any>[] = [];\n if (stale.length > 0) {\n const rebuilt = await Promise.all(\n stale.map((c) =>\n createWalletConnector<string, IProvider, any>({\n // `persistent: false` — this rebuild only re-detects providers; the\n // stored-session reconnect is done explicitly in step 2 so it can\n // also cover connectors an earlier detect-only pass already swapped in.\n persistent: false,\n metadata: metadata[c.id as keyof ChainMetadataMap]!,\n context,\n config: config.find((cc) => cc.chain === c.id)?.config,\n accountStorage: storage,\n disabledWallets,\n }).catch(() => null),\n ),\n );\n if (cancelled) return;\n\n // Keep only chains where a wallet that was NOT installed before is\n // installed now (robust to the injectable-wallet de-dup reshaping the\n // list, vs. a plain installed-count comparison).\n const appeared = rebuilt.filter((c): c is WalletConnector<string, IProvider, any> => {\n if (!c) return false;\n const before = connectorsRef.current[c.id as keyof Connectors];\n if (!before || before.connectedWallet) return false;\n const wasInstalled = new Set(before.wallets.filter((w) => w.installed).map((w) => w.id));\n return c.wallets.some((w) => w.installed && !wasInstalled.has(w.id));\n });\n\n // These chains late-injected — mark them eligible for stored-session\n // restore (carried across passes, so a detect-only modal-open pass is\n // still restored by a later cold-start pass).\n for (const c of appeared) pendingRestore.add(c.id);\n\n // Swap in the appeared connectors whose currently-in-state counterpart\n // hasn't connected in the meantime. Computed synchronously (not inside\n // the updater) so it doesn't depend on side effects in the deferred /\n // possibly double-invoked state updater.\n const current = connectorsRef.current;\n swapIn = appeared.filter((c) => !current[c.id as keyof Connectors]?.connectedWallet);\n if (swapIn.length > 0) {\n setConnectors((prev) => {\n const next: Record<string, WalletConnector<string, IProvider, any>> = {};\n for (const c of swapIn) {\n // Re-check at commit time for the tiny window since `swapIn` was computed.\n if (prev[c.id as keyof Connectors]?.connectedWallet) continue;\n next[c.id] = c;\n }\n return Object.keys(next).length > 0 ? ({ ...prev, ...next } as Connectors) : prev;\n });\n }\n }\n\n // 2. Restore persisted sessions (cold-start triggers only — the modal-open\n // trigger stays detect-only so it can't race a manual connect). Only\n // chains in `pendingRestore` (late-injected this session) are eligible,\n // so ETH/AppKit and normally-detected wallets are never reconnected\n // here. The in-state instance is taken from swapIn (this pass) or\n // current, so a session swapped in by an earlier detect-only pass is\n // still restored.\n if (!allowReconnect || !persistent || pendingRestore.size === 0) return;\n const inState: Record<string, WalletConnector<string, IProvider, any>> = {};\n for (const c of Object.values(connectorsRef.current)) {\n if (c) inState[c.id] = c as WalletConnector<string, IProvider, any>;\n }\n for (const c of swapIn) inState[c.id] = c;\n\n const reconnectTargets = selectRedetectReconnectTargets({\n connectors: Object.values(inState),\n storage,\n allowReconnect,\n persistent,\n eligibleChainIds: pendingRestore,\n });\n for (const { connector, walletId } of reconnectTargets) {\n if (reconnecting.has(connector.id)) continue;\n reconnecting.add(connector.id);\n // Fire-and-forget: `connect` swallows its own errors (returns null on\n // failure); a locked/unresponsive wallet must not block re-detection.\n // The connect event flows through the normal ChainProvider bump /\n // BTCWalletProvider / selectWallet wiring (which repopulates selectedWallets).\n void connector\n .connect(walletId)\n .then((wallet) => {\n reconnecting.delete(connector.id);\n // Restored — stop treating this chain as pending so later cold-start\n // passes don't reconnect it again. On failure `connect` resolves\n // null, so it stays pending and a later trigger retries.\n if (wallet) pendingRestore.delete(connector.id);\n })\n .catch(() => reconnecting.delete(connector.id));\n }\n };\n\n const redetectColdStart = () => void redetect(true);\n const redetectInteractive = () => void redetect(false);\n\n const timer = setTimeout(redetectColdStart, FALLBACK_MS);\n const hasWindow = typeof window !== \"undefined\";\n if (hasWindow) {\n // Cold-start race: re-detect (and restore the stored session) once the\n // extension signals it is ready.\n window.addEventListener(UNISAT_READY_EVENT, redetectColdStart, { once: true });\n // Catch-all for an injection slower than FALLBACK_MS: re-detect whenever\n // the user opens the modal. Repeatable (not `once`); the in-flight guard\n // and the no-stale-wallets early-return keep it cheap when nothing changed.\n // Detect-only (no reconnect) so it can't race the user's manual connect.\n window.addEventListener(WALLET_MODAL_OPEN_EVENT, redetectInteractive);\n }\n\n return () => {\n cancelled = true;\n clearTimeout(timer);\n if (hasWindow) {\n window.removeEventListener(UNISAT_READY_EVENT, redetectColdStart);\n window.removeEventListener(WALLET_MODAL_OPEN_EVENT, redetectInteractive);\n }\n };\n }, [connectorsBuilt, config, context, storage, disabledWallets, setConnectors, persistent, metadata]);\n}\n","\"use client\";\n\nimport { type Dispatch, type SetStateAction, useEffect, useState } from \"react\";\n\nexport function usePersistState<S>(key: string, storage: Storage, initialState: S): [S, Dispatch<SetStateAction<S>>] {\n function getDefaultState() {\n const defaultValue = typeof initialState === \"function\" ? (initialState as () => S)() : initialState;\n\n if (typeof storage === \"undefined\") {\n return defaultValue;\n }\n\n const persistValue = storage.getItem(key);\n const defaultState = persistValue ? (JSON.parse(persistValue) as S) : null;\n\n return (defaultState ?? defaultValue) as S;\n }\n\n const [state, setState] = useState<S>(getDefaultState);\n\n useEffect(\n function updateLocalStorage() {\n storage.setItem(key, JSON.stringify(state ?? \"\"));\n },\n [key, storage, state],\n );\n\n return [state, setState];\n}\n","import { createContext, PropsWithChildren, useContext, useMemo } from \"react\";\n\nimport { usePersistState } from \"@/hooks/usePersistState\";\n\ninterface InscriptionContext {\n lockInscriptions: boolean;\n toggleLockInscriptions?: (value: boolean) => void;\n}\n\nconst Context = createContext<InscriptionContext>({ lockInscriptions: true });\n\nexport function InscriptionProvider({ children, context }: PropsWithChildren<{ context: any }>) {\n const [lockInscriptions, toggleLockInscriptions] = usePersistState(\n \"bwc-inscription-modal-lock\",\n context.localStorage,\n true,\n );\n\n const inscriptionContext = useMemo(\n () => ({\n lockInscriptions,\n toggleLockInscriptions,\n }),\n [lockInscriptions, toggleLockInscriptions],\n );\n\n return <Context.Provider value={inscriptionContext}>{children}</Context.Provider>;\n}\n\nexport const useInscriptionProvider = () => useContext(Context);\n","import { DISCONNECT_EVENT, NETWORK_CHANGE_EVENT } from \"@/constants/walletEvents\";\nimport type { Connectors } from \"@/context/Chain.context\";\nimport type { Account, ChainId, IBTCProvider, IETHProvider, IProvider, IWallet } from \"@/core/types\";\n\nexport const WALLET_CONFIRMATION_RECEIPT_KEY = \"__babylon-wallet-confirmation-v1__\";\n\nconst RECEIPT_VERSION = 2;\n\nexport interface ConfirmationConnection {\n chain: ChainId;\n wallet: IWallet;\n account: Account;\n}\n\ninterface ConfirmationReceiptEntry {\n chain: ChainId;\n walletId: string;\n address: string;\n publicKeyHex: string;\n network: string;\n}\n\ninterface ConfirmationReceipt {\n version: typeof RECEIPT_VERSION;\n entries: ConfirmationReceiptEntry[];\n}\n\nconst IDENTITY_CHANGE_EVENTS: Record<ChainId, readonly string[]> = {\n BTC: [\"accountsChanged\", NETWORK_CHANGE_EVENT, DISCONNECT_EVENT],\n BBN: [\"accountChanged\"],\n ETH: [\"accountsChanged\", \"chainChanged\"],\n};\n\ntype IdentityEventProvider = IProvider & {\n on?: (event: string, handler: (...args: unknown[]) => void) => void;\n off?: (event: string, handler: (...args: unknown[]) => void) => void;\n};\n\nfunction connectorFor(connectors: Connectors, chain: ChainId) {\n return connectors[chain];\n}\n\n/**\n * The network a chain's connector is pointed at. A receipt approved on signet\n * must not restore a session against mainnet, so this participates in the\n * match alongside the account identity.\n */\nfunction networkIdentity(\n connectors: Connectors,\n chain: ChainId,\n networks?: Partial<Record<ChainId, string | number>>,\n): string {\n const config = connectorFor(connectors, chain)?.config as\n | { chainId?: string | number; network?: string | number }\n | undefined;\n const value = networks?.[chain] ?? (chain === \"BTC\" ? config?.network : config?.chainId);\n\n return value === undefined ? \"\" : String(value);\n}\n\nexport function sameIdentity(left: string, right: string): boolean {\n return left.toLowerCase() === right.toLowerCase();\n}\n\nfunction isReceiptEntry(value: unknown): value is ConfirmationReceiptEntry {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\n const entry = value as Partial<ConfirmationReceiptEntry>;\n\n return (\n typeof entry.chain === \"string\" &&\n typeof entry.walletId === \"string\" &&\n typeof entry.address === \"string\" &&\n typeof entry.publicKeyHex === \"string\" &&\n typeof entry.network === \"string\"\n );\n}\n\nfunction parseConfirmationReceipt(serialized: string | undefined): ConfirmationReceipt | undefined {\n if (!serialized) return;\n\n try {\n const receipt = JSON.parse(serialized) as Partial<ConfirmationReceipt>;\n if (\n receipt?.version !== RECEIPT_VERSION ||\n !Array.isArray(receipt.entries) ||\n !receipt.entries.every(isReceiptEntry)\n ) {\n return;\n }\n\n return receipt as ConfirmationReceipt;\n } catch {\n return;\n }\n}\n\n/**\n * Serializes what the user approved: the wallet, account and network of every\n * chain connected at the moment they confirmed.\n *\n * Deliberately records the connected set rather than the required set. A host\n * that varies its requirements per route would otherwise mint a receipt on one\n * route that cannot satisfy the next, and sign the user out on navigation.\n */\nexport function createConfirmationReceipt(\n connections: readonly ConfirmationConnection[],\n connectors: Connectors,\n networks?: Partial<Record<ChainId, string | number>>,\n): string {\n const entries = connections\n .filter((connection) => connection.account && connectorFor(connectors, connection.chain))\n .map<ConfirmationReceiptEntry>((connection) => ({\n chain: connection.chain,\n walletId: connection.wallet.id,\n address: connection.account.address,\n publicKeyHex: connection.account.publicKeyHex,\n network: networkIdentity(connectors, connection.chain, networks),\n }))\n .sort((left, right) => left.chain.localeCompare(right.chain));\n\n return JSON.stringify({ version: RECEIPT_VERSION, entries } satisfies ConfirmationReceipt);\n}\n\n/**\n * True when the stored approval covers every currently-required chain and each\n * one still matches the live connection.\n *\n * Coverage, not equality: a receipt may name chains that are not required right\n * now, which is what lets a host narrow and widen its requirements — per route,\n * say — without invalidating an approval the user already gave. A required\n * chain the receipt does not name is never covered, so consent is still never\n * inherited by a chain, account, wallet or network the user did not approve.\n */\nexport function isValidConfirmationReceipt(\n serialized: string | undefined,\n requiredChainIds: readonly string[],\n connectors: Connectors,\n): boolean {\n const entries = parseConfirmationReceipt(serialized)?.entries;\n if (!entries) return false;\n\n // An empty requirement set is satisfied by any receipt, but never by none:\n // the caller still has to have an approval on file.\n return requiredChainIds.every((chainId) => {\n const chain = chainId as ChainId;\n const wallet = connectorFor(connectors, chain)?.connectedWallet;\n const account = wallet?.account;\n const entry = entries.find((candidate) => candidate.chain === chain);\n\n return Boolean(\n wallet &&\n account &&\n entry &&\n entry.walletId === wallet.id &&\n sameIdentity(entry.address, account.address) &&\n sameIdentity(entry.publicKeyHex, account.publicKeyHex) &&\n entry.network === networkIdentity(connectors, chain),\n );\n });\n}\n\nexport function isConfirmationReceiptCovered(\n serialized: string | undefined,\n requiredChainIds: readonly string[],\n connectors: Connectors,\n): boolean {\n const entries = parseConfirmationReceipt(serialized)?.entries;\n if (!entries) return false;\n\n return requiredChainIds.every((chainId) => {\n const chain = chainId as ChainId;\n const wallet = connectorFor(connectors, chain)?.connectedWallet;\n const entry = entries.find((candidate) => candidate.chain === chain);\n\n return Boolean(\n wallet && entry && entry.walletId === wallet.id && entry.network === networkIdentity(connectors, chain),\n );\n });\n}\n\n/** Checks the current provider values instead of the connector's cached account. */\nexport async function isLiveConfirmationReceiptValid(\n serialized: string | undefined,\n requiredChainIds: readonly string[],\n connectors: Connectors,\n): Promise<boolean> {\n const entries = parseConfirmationReceipt(serialized)?.entries;\n if (!entries) return false;\n\n const matches = await Promise.all(\n requiredChainIds.map(async (chainId) => {\n const chain = chainId as ChainId;\n const connector = connectorFor(connectors, chain);\n const wallet = connector?.connectedWallet;\n const provider = wallet?.provider;\n const entry = entries.find((candidate) => candidate.chain === chain);\n if (!wallet || !provider || !entry || entry.walletId !== wallet.id) return false;\n\n try {\n if (provider.isIdentityCurrent?.() === false) return false;\n const [address, publicKeyHex, network] = await Promise.all([\n provider.getAddress(),\n provider.getPublicKeyHex(),\n chain === \"ETH\"\n ? (provider as IETHProvider).getChainId()\n : chain === \"BTC\"\n ? (provider as IBTCProvider).getNetwork()\n : networkIdentity(connectors, chain),\n ]);\n if (provider.isIdentityCurrent?.() === false) return false;\n\n return (\n sameIdentity(entry.address, address) &&\n sameIdentity(entry.publicKeyHex, publicKeyHex) &&\n entry.network === String(network)\n );\n } catch {\n return false;\n }\n }),\n );\n\n return matches.every(Boolean);\n}\n\nexport function subscribeToConfirmationIdentityChanges(\n serialized: string,\n requiredChainIds: readonly string[],\n connectors: Connectors,\n onChange: (chain: ChainId) => void,\n): () => void {\n const entries = parseConfirmationReceipt(serialized)?.entries;\n if (!entries) return () => {};\n\n const subscriptions: Array<{\n event: string;\n handler: (...args: unknown[]) => void;\n provider: IdentityEventProvider;\n }> = [];\n\n requiredChainIds.forEach((chainId) => {\n const chain = chainId as ChainId;\n const provider = connectors[chain]?.connectedWallet?.provider as IdentityEventProvider | null | undefined;\n if (!provider?.on) return;\n\n IDENTITY_CHANGE_EVENTS[chain]?.forEach((event) => {\n const handler = (...args: unknown[]) => {\n const accounts = args[0];\n const approved = entries.find((entry) => entry.chain === chain);\n if (\n chain === \"ETH\" &&\n event === \"accountsChanged\" &&\n Array.isArray(accounts) &&\n accounts.length === 1 &&\n typeof accounts[0] === \"string\" &&\n approved &&\n sameIdentity(approved.address, accounts[0])\n ) {\n return;\n }\n\n onChange(chain);\n };\n\n try {\n provider.on?.(event, handler);\n subscriptions.push({ event, handler, provider });\n } catch {\n // Some wallet adapters reject event names they do not support.\n }\n });\n });\n\n return () => {\n subscriptions.forEach(({ event, handler, provider }) => {\n try {\n provider.off?.(event, handler);\n } catch {\n // The provider can disconnect before the listener is removed.\n }\n });\n };\n}\n\n/** Chains the stored approval names, whether or not they are required now. */\nexport function confirmedChains(serialized: string | undefined): ChainId[] {\n return parseConfirmationReceipt(serialized)?.entries.map((entry) => entry.chain) ?? [];\n}\n","import { type PropsWithChildren, createContext, useEffect, useInsertionEffect, useMemo, useRef, useState } from \"react\";\n\nimport { WALLET_MODAL_OPEN_EVENT } from \"@/constants/walletEvents\";\nimport { WALLET_CONFIRMATION_RECEIPT_KEY } from \"@/core/confirmationReceipt\";\nimport type { HashMap, IChain, IWallet } from \"@/core/types\";\n\nexport type Screen<T extends string = string> = {\n type: T;\n params?: Record<string, any>;\n};\n\nexport type Screens =\n | Screen<\"LOADER\">\n | Screen<\"CHAINS\">\n | Screen<\"WALLETS\">\n | Screen<\"ERROR\">;\n\nexport interface State {\n confirmed: boolean;\n /** The wallet identity that the user approved for this live session. */\n confirmationReceipt?: string;\n visible: boolean;\n screen: Screens;\n selectedWallets: Record<string, IWallet | undefined>;\n /** Every chain the dialog displays. */\n chains: Record<string, IChain>;\n /**\n * The subset of `chains` a host requires before the session counts as\n * connected. Chains outside this set are offered but never block confirm.\n */\n requiredChainIds: string[];\n}\n\nexport interface Actions {\n open?: () => void;\n close?: () => void;\n displayLoader?: (message?: string, description?: string) => void;\n displayChains?: () => void;\n displayWallets?: (chain: string) => void;\n displayError?: (params: {\n icon?: JSX.Element;\n title: string;\n description: string;\n cancelButton?: string;\n submitButton?: string;\n onCancel?: () => void;\n onSubmit?: () => void;\n }) => void;\n selectWallet?: (chain: string, wallet: IWallet) => void;\n removeWallet?: (chain: string) => void;\n confirm?: (receipt: string) => void;\n /** Withdraws the confirmation without disconnecting anything. */\n unconfirm?: (keepReceipt?: boolean) => void;\n reset?: () => void;\n}\n\nconst defaultState: State = {\n confirmed: false,\n visible: false,\n screen: { type: \"CHAINS\" },\n chains: {},\n selectedWallets: {},\n requiredChainIds: [],\n};\n\nexport const StateContext = createContext<State & Actions>(defaultState);\n\ninterface StateProviderProps {\n chains: IChain[];\n requiredChainIds: readonly string[];\n storage?: HashMap;\n}\n\n// Filters selected wallets to only include those that belong to currently valid chains.\n// This ensures wallet state stays in sync when the available chains configuration changes.\nfunction filterWalletsByValidChains(\n selectedWallets: Record<string, IWallet | undefined>,\n validChainIds: Set<string>\n): Record<string, IWallet | undefined> {\n return Object.keys(selectedWallets).reduce((acc, key) => {\n if (validChainIds.has(key)) {\n acc[key] = selectedWallets[key];\n }\n return acc;\n }, {} as Record<string, IWallet | undefined>);\n}\n\nexport function StateProvider({ children, chains, requiredChainIds, storage }: PropsWithChildren<StateProviderProps>) {\n const [state, setState] = useState<State>(() => ({\n ...defaultState,\n chains: chains.reduce((acc, chain) => ({ ...acc, [chain.id]: chain }), {}),\n requiredChainIds: [...requiredChainIds],\n }));\n const requirementsExpanded = requiredChainIds.some((chainId) => !state.requiredChainIds.includes(chainId));\n const renderedState = useMemo(\n () => ({\n ...state,\n confirmed: requirementsExpanded ? false : state.confirmed,\n requiredChainIds: [...requiredChainIds],\n }),\n [requiredChainIds, requirementsExpanded, state],\n );\n const requiredChainIdsRef = useRef(requiredChainIds);\n useInsertionEffect(() => {\n requiredChainIdsRef.current = requiredChainIds;\n }, [requiredChainIds]);\n // Expose new requirements as unconfirmed during render. This prevents a\n // child from observing one approved commit before live validation starts.\n useEffect(() => {\n setState((state) => {\n const newChains = chains.reduce((acc, chain) => ({ ...acc, [chain.id]: chain }), {});\n const validChainIds = new Set(chains.map((chain) => chain.id));\n const filteredWallets = filterWalletsByValidChains(state.selectedWallets, validChainIds);\n const requirementsExpanded = requiredChainIds.some((chainId) => !state.requiredChainIds.includes(chainId));\n\n return {\n ...state,\n confirmed: requirementsExpanded ? false : state.confirmed,\n chains: newChains,\n selectedWallets: filteredWallets,\n requiredChainIds: [...requiredChainIds],\n };\n });\n }, [chains, requiredChainIds]);\n\n const actions: Actions = useMemo(\n () => ({\n open: () => {\n // Let late-injection re-detection (useWalletRedetection) re-check for\n // wallets that injected after the initial detection before the user\n // sees the wallet list — otherwise a slow extension shows as a\n // download link until the next reload.\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(WALLET_MODAL_OPEN_EVENT));\n }\n setState((state) => ({ ...state, visible: true }));\n },\n\n close: () => {\n setState((state) => ({ ...state, visible: false }));\n },\n\n reset: () => {\n storage?.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n setState(({ chains, requiredChainIds }) => ({ ...defaultState, chains, requiredChainIds }));\n },\n\n displayLoader: (message = \"\", description = \"\") => {\n setState((state) => ({ ...state, screen: { type: \"LOADER\", params: { message, description } } }));\n },\n\n displayChains: () => {\n setState((state) => ({ ...state, screen: { type: \"CHAINS\" } }));\n },\n\n displayWallets: (chain: string) => {\n setState((state) => ({ ...state, screen: { type: \"WALLETS\", params: { chain } } }));\n },\n\n displayError: (params) => {\n setState((state) => ({ ...state, screen: { type: \"ERROR\", params } }));\n },\n\n selectWallet: (chain: string, wallet: IWallet) => {\n setState((state) => ({\n ...state,\n selectedWallets: { ...state.selectedWallets, [chain]: wallet },\n }));\n },\n\n removeWallet: (chain: string) => {\n const required = requiredChainIdsRef.current.includes(chain);\n if (required) {\n storage?.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n }\n setState((state) => ({\n ...state,\n // Losing an optional chain must not tear down a confirmed session.\n // Losing a required one does invalidate the confirmation, so\n // reconnecting cannot silently restore it.\n confirmed: required ? false : state.confirmed,\n confirmationReceipt: required ? undefined : state.confirmationReceipt,\n selectedWallets: { ...state.selectedWallets, [chain]: undefined },\n }));\n },\n\n confirm: (confirmationReceipt: string) => {\n setState((state) => ({ ...state, confirmed: true, confirmationReceipt }));\n },\n\n unconfirm: (keepReceipt = false) => {\n setState((state) => ({\n ...state,\n confirmed: false,\n confirmationReceipt: keepReceipt ? state.confirmationReceipt : undefined,\n }));\n },\n }),\n [storage],\n );\n\n const context = useMemo(\n () => ({\n ...renderedState,\n ...actions,\n }),\n [renderedState, actions],\n );\n\n return <StateContext.Provider value={context}>{children}</StateContext.Provider>;\n}\n","import { createContext, PropsWithChildren, useCallback, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport { createWalletConnector } from \"@/core\";\nimport { WalletConnector } from \"@/core/WalletConnector\";\nimport type {\n BBNConfig,\n BTCConfig,\n ChainId,\n ChainMetadata,\n ETHConfig,\n ExternalConnector,\n HashMap,\n IBBNProvider,\n IBTCProvider,\n IETHProvider,\n IProvider,\n} from \"@/core/types\";\nimport { useWalletRedetection } from \"@/hooks/useWalletRedetection\";\n\nimport { InscriptionProvider } from \"./Inscriptions.context\";\nimport { StateProvider } from \"./State.context\";\n\nexport interface ChainConfig<K extends string = string, P extends IProvider = IProvider, C = any> {\n chain: K;\n name?: string;\n icon?: string;\n config: C;\n connectors?: ExternalConnector<P>[];\n}\n\nexport type ChainConfigArr = (\n | ChainConfig<\"BTC\", IBTCProvider, BTCConfig>\n | ChainConfig<\"BBN\", IBBNProvider, BBNConfig>\n | ChainConfig<\"ETH\", IETHProvider, ETHConfig>\n)[];\n\n/**\n * Chain metadata is injected rather than imported, so an entry point can hand\n * over only the chains it supports. The `./eth` entry passes `{ ETH }` alone,\n * which keeps every Bitcoin wallet adapter out of its module graph.\n */\nexport interface ChainMetadataMap {\n BTC?: ChainMetadata<\"BTC\", IBTCProvider, BTCConfig>;\n BBN?: ChainMetadata<\"BBN\", IBBNProvider, BBNConfig>;\n ETH?: ChainMetadata<\"ETH\", IETHProvider, ETHConfig>;\n}\n\ninterface ProviderProps {\n persistent: boolean;\n storage: HashMap;\n context: any;\n config: Readonly<ChainConfigArr>;\n onError?: (e: Error) => void;\n disabledWallets?: string[];\n /** Defaults to every configured chain, which is the pre-optional-chains behaviour. */\n requiredChains?: readonly ChainId[];\n metadata: ChainMetadataMap;\n}\n\nexport interface Connectors {\n BTC: WalletConnector<\"BTC\", IBTCProvider, BTCConfig> | null;\n BBN: WalletConnector<\"BBN\", IBBNProvider, BBNConfig> | null;\n ETH: WalletConnector<\"ETH\", IETHProvider, ETHConfig> | null;\n}\n\nconst defaultState: Connectors = {\n BTC: null,\n BBN: null,\n ETH: null,\n};\n\nexport const Context = createContext<Connectors>(defaultState);\n\nexport function ChainProvider({\n persistent,\n storage,\n children,\n context,\n config,\n onError,\n disabledWallets,\n requiredChains,\n metadata,\n}: PropsWithChildren<ProviderProps>) {\n const [connectors, setConnectors] = useState(defaultState);\n\n const init = useCallback(async () => {\n const filteredConfig = config.filter((c) => metadata[c.chain]);\n\n const connectorPromises = filteredConfig.map(async ({ chain, config }) => {\n const chainMetadata = metadata[chain];\n if (!chainMetadata) return null;\n\n try {\n const connector = await createWalletConnector<string, IProvider, any>({\n persistent,\n metadata: chainMetadata,\n context,\n config,\n accountStorage: storage,\n disabledWallets,\n });\n return connector;\n } catch (error) {\n console.error(\"[ChainProvider] failed to create connector for chain:\", chain, error instanceof Error ? error.message : \"Unknown error\");\n throw error;\n }\n });\n\n const connectorArr = await Promise.all(connectorPromises);\n\n return connectorArr.reduce<Connectors>(\n (acc, connector) => (connector ? { ...acc, [connector.id]: connector } : acc),\n { ...defaultState },\n );\n }, [persistent, config, context, storage, disabledWallets, metadata]);\n\n useEffect(() => {\n init()\n .then((connectors) => {\n setConnectors(connectors);\n })\n .catch((error) => {\n console.error(\"[ChainProvider] init failed with error:\", error instanceof Error ? error.message : \"Unknown error\");\n onError?.(error);\n });\n }, [setConnectors, init, onError]);\n\n // Re-detect wallets whose extension injected after the one-shot detection\n // in `init()` above (e.g. UniSat's late `window.unisat` injection).\n useWalletRedetection({ connectors, setConnectors, config, context, storage, disabledWallets, persistent, metadata });\n\n // Auto-reconnect (and any other connect/disconnect) mutates `connectedWallet`\n // on the existing connector instance without changing the `connectors` object\n // identity, so consumers that read `connector.connectedWallet` reactively —\n // e.g. the auto-confirm-on-reload effect in `useWalletConnectors` — would not\n // re-evaluate. Because the BTC reconnect is now fire-and-forget (see\n // `createWalletConnector`), that mutation lands *after* the connectors are in\n // state. Bump a fresh `connectors` object on each connect/disconnect so those\n // consumers re-render and observe the new connection state.\n useEffect(() => {\n const active = Object.values(connectors).filter(Boolean) as WalletConnector<string, IProvider, any>[];\n if (active.length === 0) return;\n\n const bump = () => setConnectors((prev) => ({ ...prev }));\n const unsubscribe = active.flatMap((connector) => [connector.on(\"connect\", bump), connector.on(\"disconnect\", bump)]);\n\n return () => unsubscribe.forEach((fn) => fn());\n }, [connectors]);\n\n // Every chain that built a connector is displayed. `requiredChains` used to\n // filter this list, which meant a host could not offer a wallet without also\n // demanding it; it now gates only the confirm button and session restore.\n const supportedChains = useMemo(\n () => Object.values(connectors).filter((connector): connector is NonNullable<typeof connector> => Boolean(connector)),\n [connectors],\n );\n const requiredChainIds = useMemo(\n () =>\n requiredChains === undefined\n ? config.filter((entry) => metadata[entry.chain]).map((entry) => entry.chain)\n : [...requiredChains],\n [config, metadata, requiredChains],\n );\n\n return (\n <InscriptionProvider context={context}>\n <StateProvider chains={supportedChains} requiredChainIds={requiredChainIds} storage={storage}>\n <Context.Provider value={connectors}>{children}</Context.Provider>\n </StateProvider>\n </InscriptionProvider>\n );\n}\n\nexport const useChainProviders = () => {\n return useContext(Context);\n};\n","import { createContext, PropsWithChildren, useContext, useMemo } from \"react\";\n\nimport type { Account, ChainId, IWallet } from \"@/core/types\";\n\nexport interface WalletLifecycleConnection {\n chain: ChainId;\n wallet: IWallet;\n account: Account;\n}\n\nexport interface TermsOfServiceParams {\n /**\n * Address of the connected account for the first required chain. Read\n * `connections` instead whenever the chain the address belongs to matters —\n * this is a Bitcoin account only for hosts that require Bitcoin first.\n */\n address: string;\n /** Public key of that same account. Read `connections` instead when the chain matters. */\n public_key: string;\n chain: ChainId;\n connections: WalletLifecycleConnection[];\n}\n\nexport interface LifeCycleHooksProps {\n verifyBTCAddress?: (address: string) => Promise<boolean>;\n /**\n * Fires once when the user confirms the wallet dialog, not when an\n * individual wallet connects, and is skipped when an already-confirmed\n * session is confirmed again.\n */\n acceptTermsOfService?: (params: TermsOfServiceParams) => Promise<void>;\n onConfirm?: (connections: WalletLifecycleConnection[]) => void | Promise<void>;\n}\n\nconst Context = createContext<LifeCycleHooksProps>({});\n\nexport function LifeCycleHooksProvider({ children, value }: PropsWithChildren<{ value?: LifeCycleHooksProps }>) {\n const context = useMemo(() => {\n return value ?? {};\n }, [value]);\n\n return <Context.Provider value={context}>{children}</Context.Provider>;\n}\n\nexport const useLifeCycleHooks = () => useContext(Context);\n","import type { HashMap } from \"./types\";\n\nconst CONNECTED_ACCOUNTS_KEY = \"baby-connected-wallet-accounts\";\n\n/**\n * Scopes a chain key with its network identifier so that persisted\n * wallet connections from one network are not auto-restored on another.\n * e.g. \"BTC\" with network \"mainnet\" → \"BTC:mainnet\"\n */\nfunction scopeKey(key: string, networkMap?: Record<string, string>): string {\n const network = networkMap?.[key];\n return network ? `${key}:${network}` : key;\n}\n\n/**\n * Safely reads and parses the connected accounts map from localStorage.\n * On parse failure (corrupted data), clears the corrupted entry and returns an empty map.\n */\nfunction readAccountsMap(): Record<string, unknown> {\n const raw = localStorage.getItem(CONNECTED_ACCOUNTS_KEY);\n if (!raw) return {};\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n localStorage.removeItem(CONNECTED_ACCOUNTS_KEY);\n return {};\n }\n return parsed as Record<string, unknown>;\n } catch (e) {\n console.error(\"[account-storage] Failed to parse accounts map, clearing corrupted entry:\", e);\n localStorage.removeItem(CONNECTED_ACCOUNTS_KEY);\n return {};\n }\n}\n\n/**\n * Safely writes the accounts map to localStorage.\n * On write failure (quota exceeded, serialization error), clears the entry to avoid stale state.\n */\nfunction writeAccountsMap(map: Record<string, unknown>): void {\n try {\n localStorage.setItem(CONNECTED_ACCOUNTS_KEY, JSON.stringify(map));\n } catch (e) {\n console.error(\"[account-storage] Failed to write accounts map, clearing entry:\", e);\n localStorage.removeItem(CONNECTED_ACCOUNTS_KEY);\n }\n}\n\n/**\n * Factory method instantiates an instance of persistent key value storage with predefined ttl value\n * @param ttl - time to live in ms\n * @param networkMap - maps chain IDs to their network identifiers (e.g. { BTC: \"mainnet\", ETH: \"1\" })\n * so entries are scoped per-network and won't cross-restore on network changes\n * @returns - key value storage\n */\nexport const createAccountStorage = (ttl: number, networkMap?: Record<string, string>): HashMap => {\n function getTimestamps(map: Record<string, unknown>): Record<string, number> {\n const timestamps = map._timestamps;\n if (timestamps && typeof timestamps === \"object\" && !Array.isArray(timestamps)) {\n return timestamps as Record<string, number>;\n }\n return {};\n }\n\n function isExpired(map: Record<string, unknown>, scoped: string): boolean {\n const timestamps = getTimestamps(map);\n const ts = timestamps[scoped];\n if (typeof ts !== \"number\" || !Number.isFinite(ts)) return true;\n\n const now = Date.now();\n // Clamp to a sane window. Without these, an XSS-tier write of\n // ts=Number.MAX_SAFE_INTEGER (or any far-future value) makes\n // `now - ts` negative and the entry never expires; a backwards\n // clock jump similarly extends entries past the intended TTL.\n if (ts < 0) return true;\n if (ts > now + ttl) return true;\n return now - ts > ttl;\n }\n\n return {\n get: (key: string) => {\n const map = readAccountsMap();\n const scoped = scopeKey(key, networkMap);\n\n if (isExpired(map, scoped)) {\n return undefined;\n }\n\n return map[scoped] as string | undefined;\n },\n has: (key: string) => {\n const map = readAccountsMap();\n const scoped = scopeKey(key, networkMap);\n\n if (isExpired(map, scoped)) {\n return false;\n }\n\n return Boolean(map[scoped]);\n },\n set: (key: string, value: string) => {\n const map = readAccountsMap();\n const scoped = scopeKey(key, networkMap);\n const timestamps = getTimestamps(map);\n\n map[scoped] = value;\n map._timestamps = { ...timestamps, [scoped]: Date.now() };\n writeAccountsMap(map);\n },\n delete: (key: string) => {\n const map = readAccountsMap();\n const scoped = scopeKey(key, networkMap);\n const timestamps = getTimestamps(map);\n\n const deleted = Reflect.deleteProperty(map, scoped);\n delete timestamps[scoped];\n map._timestamps = timestamps;\n writeAccountsMap(map);\n return deleted;\n },\n };\n};\n","// Fill shown behind wallet marks that ship as a single-colour glyph with no\n// background of their own (OKX, Ledger, Keystone, OneKey). Without it the mark\n// disappears against a same-coloured surface — black glyphs vanish in dark mode.\n// Wallets whose logo already carries its own colour (MetaMask, UniSat, Keplr)\n// leave `iconBackground` undefined and render bare.\nexport const MONOCHROME_MARK_BACKGROUND = \"#000000\";\n\nexport const ONEKEY_BRAND_GREEN = \"#1FE121\";\n","export default \"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20width='225px'%20height='224px'%20viewBox='0%200%20225%20224'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3ctitle%3eokx%3c/title%3e%3cg%20id='Page-1'%20stroke='none'%20strokeWidth='1'%20fill='none'%20fill-rule='evenodd'%3e%3cg%20id='okx'%20transform='translate(0.401000,%200.006000)'%20fill='%23FFFFFF'%20fill-rule='nonzero'%3e%3cpath%20d='M144.382,74.667%20L79.673,74.667%20C76.924,74.667%2074.695,76.895%2074.695,79.644%20L74.695,144.354%20C74.695,147.103%2076.924,149.332%2079.673,149.332%20L144.382,149.332%20C147.131,149.332%20149.36,147.103%20149.36,144.354%20L149.36,79.644%20C149.36,76.895%20147.131,74.667%20144.382,74.667%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M69.687,0%20L4.978,0%20C2.229,0%200,2.228%200,4.978%20L0,69.687%20C0,72.436%202.229,74.665%204.978,74.665%20L69.687,74.665%20C72.437,74.665%2074.665,72.436%2074.665,69.687%20L74.665,4.978%20C74.665,2.228%2072.437,0%2069.687,0%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M219.017,0%20L154.307,0%20C151.558,0%20149.329,2.228%20149.329,4.978%20L149.329,69.687%20C149.329,72.436%20151.558,74.665%20154.307,74.665%20L219.017,74.665%20C221.766,74.665%20223.994,72.436%20223.994,69.687%20L223.994,4.978%20C223.994,2.228%20221.766,0%20219.017,0%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M69.687,149.328%20L4.978,149.328%20C2.229,149.328%200,151.556%200,154.305%20L0,219.015%20C0,221.764%202.229,223.993%204.978,223.993%20L69.687,223.993%20C72.437,223.993%2074.665,221.764%2074.665,219.015%20L74.665,154.305%20C74.665,151.556%2072.437,149.328%2069.687,149.328%20Z'%20id='Path'%3e%3c/path%3e%3cpath%20d='M219.017,149.328%20L154.307,149.328%20C151.558,149.328%20149.329,151.556%20149.329,154.305%20L149.329,219.015%20C149.329,221.764%20151.558,223.993%20154.307,223.993%20L219.017,223.993%20C221.766,223.993%20223.994,221.764%20223.994,219.015%20L223.994,154.305%20C223.994,151.556%20221.766,149.328%20219.017,149.328%20Z'%20id='Path'%3e%3c/path%3e%3c/g%3e%3c/g%3e%3c/svg%3e\"","/**\n * Event dispatched to open the AppKit modal\n *\n * Both ETH and BTC AppKit connectors dispatch this event to trigger\n * the unified AppKit modal opening.\n */\nexport const APPKIT_OPEN_EVENT = \"babylon:open-appkit\";\n\n/**\n * Connector ids live here rather than beside their wallet metadata so a\n * consumer can match on one without importing the other chain's metadata\n * module — the `./eth` entry reads `APPKIT_ETH_CONNECTOR_ID` and must not pull\n * `btc/appkit` in with it.\n */\nexport const APPKIT_ETH_CONNECTOR_ID = \"appkit-eth-connector\";\nexport const APPKIT_BTC_CONNECTOR_ID = \"appkit-btc-connector\";\n","import type { createAppKit } from \"@reown/appkit/react\";\nimport type { Chain } from \"viem\";\nimport type { Config } from \"wagmi\";\n\nimport { ERROR_CODES, WalletError } from \"@/error\";\n\nimport type { SharedBtcAppKitConfig } from \"../btc/appkit/sharedConfig\";\n\nexport type AppKitModal = ReturnType<typeof createAppKit>;\n\ninterface AppKitMetadata {\n name: string;\n description: string;\n url: string;\n icons: readonly string[];\n}\n\nexport interface AppKitCapabilities {\n readonly projectId: string;\n readonly metadataFingerprint: string;\n readonly ethFingerprint?: string;\n readonly btcNetwork?: \"mainnet\" | \"signet\";\n}\n\nexport interface AppKitState extends AppKitCapabilities {\n readonly modal: AppKitModal;\n readonly wagmiConfig?: Config;\n readonly btcConfig?: SharedBtcAppKitConfig;\n}\n\nconst BIGINT_FINGERPRINT_TYPE = \"bigint\";\nconst FUNCTION_FINGERPRINT_TYPE = \"function\";\nconst CONFIG_FINGERPRINT_SERIALIZATION_ERROR = \"AppKit configuration cannot be serialized.\";\nconst INITIAL_CONFIG_FUNCTION_ID = 1;\nconst configFunctionIds = new WeakMap<object, number>();\nlet nextConfigFunctionId = INITIAL_CONFIG_FUNCTION_ID;\n\nfunction getConfigFunctionId(value: object): number {\n const existingId = configFunctionIds.get(value);\n if (existingId) return existingId;\n\n const id = nextConfigFunctionId++;\n configFunctionIds.set(value, id);\n return id;\n}\n\nfunction createConfigFingerprint(value: object): string {\n const fingerprint = JSON.stringify(value, (_key, nestedValue) => {\n if (typeof nestedValue === BIGINT_FINGERPRINT_TYPE) {\n return { type: BIGINT_FINGERPRINT_TYPE, value: nestedValue.toString() };\n }\n\n if (typeof nestedValue === FUNCTION_FINGERPRINT_TYPE) {\n return { type: FUNCTION_FINGERPRINT_TYPE, value: getConfigFunctionId(nestedValue) };\n }\n\n if (nestedValue && typeof nestedValue === \"object\" && !Array.isArray(nestedValue)) {\n return Object.fromEntries(\n Object.entries(nestedValue).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)),\n );\n }\n\n return nestedValue;\n });\n\n if (fingerprint === undefined) {\n throw new TypeError(CONFIG_FINGERPRINT_SERIALIZATION_ERROR);\n }\n\n return fingerprint;\n}\n\nexport function createAppKitCapabilities({\n projectId,\n metadata,\n ethChain,\n btcNetwork,\n}: {\n projectId: string;\n metadata: AppKitMetadata;\n ethChain?: Chain;\n btcNetwork?: \"mainnet\" | \"signet\";\n}): AppKitCapabilities {\n return Object.freeze({\n projectId,\n metadataFingerprint: createConfigFingerprint(metadata),\n ethFingerprint: ethChain ? createConfigFingerprint(ethChain) : undefined,\n btcNetwork,\n });\n}\n\n/**\n * AppKit allows one modal instance per page. The instance is held here rather\n * than in either initializer so the unified (ETH+BTC) and Ethereum-only setups\n * observe the same singleton without the Ethereum-only one having to import\n * the Bitcoin adapter through its sibling.\n */\nlet appKitState: AppKitState | null = null;\nlet manualAppKitModal: AppKitModal | null = null;\nconst manualAppKitCapabilities = new Set<\"Ethereum\" | \"Bitcoin\">();\n\nexport function failInitialization(message: string, chainId?: string): never {\n throw new WalletError({ code: ERROR_CODES.WALLET_INITIALIZATION_FAILED, message, chainId });\n}\n\nexport function getAppKitState(): AppKitState | null {\n return appKitState;\n}\n\nexport function getAppKitModal(): AppKitModal | null {\n return appKitState?.modal ?? manualAppKitModal;\n}\n\nexport function registerManualAppKitConfig(capability: \"Ethereum\" | \"Bitcoin\", modal?: AppKitModal): void {\n if (appKitState) {\n failInitialization(\n `Cannot set a manual ${capability} AppKit configuration after AppKit initialization. Use the canonical AppKit state.`,\n );\n }\n\n manualAppKitCapabilities.add(capability);\n if (modal) manualAppKitModal = modal;\n}\n\n/** @internal */\nexport function __resetManualAppKitConfigForTests(capability: \"Ethereum\" | \"Bitcoin\"): void {\n manualAppKitCapabilities.delete(capability);\n if (capability === \"Bitcoin\") manualAppKitModal = null;\n}\n\nexport function validateAppKitInitialization(projectId?: string): projectId is string {\n if (!projectId) {\n if (appKitState) {\n failInitialization(\n \"AppKit is already initialized. A project ID is required to validate the requested configuration.\",\n );\n }\n\n return false;\n }\n\n if (manualAppKitCapabilities.size > 0) {\n failInitialization(\n `Cannot initialize AppKit after a manual ${[...manualAppKitCapabilities].join(\" and \")} configuration was set. Use only one initialization method.`,\n );\n }\n\n return true;\n}\n\nexport function setAppKitState(state: AppKitState): AppKitState {\n if (appKitState) {\n failInitialization(\"AppKit is already initialized. Reuse the shared AppKit state instead of replacing it.\");\n }\n\n if (manualAppKitCapabilities.size > 0) {\n failInitialization(\"Cannot publish AppKit state after a manual shared configuration was set.\");\n }\n\n appKitState = Object.freeze({\n ...state,\n btcConfig: state.btcConfig ? Object.freeze({ ...state.btcConfig }) : undefined,\n });\n return appKitState;\n}\n\nexport function assertAppKitCapabilities(existing: AppKitCapabilities, requested: AppKitCapabilities): void {\n if (existing.projectId !== requested.projectId) {\n failInitialization(\n \"AppKit was already initialized with a different project ID. A page can use only one AppKit configuration.\",\n );\n }\n\n if (existing.metadataFingerprint !== requested.metadataFingerprint) {\n failInitialization(\n \"AppKit was already initialized with different metadata. A page can use only one AppKit configuration.\",\n );\n }\n\n if (requested.ethFingerprint) {\n if (!existing.ethFingerprint) {\n failInitialization(\n \"AppKit was already initialized without Ethereum support. A page that needs Ethereum must initialize AppKit with Ethereum first.\",\n \"ETH\",\n );\n }\n\n if (existing.ethFingerprint !== requested.ethFingerprint) {\n failInitialization(\"AppKit was already initialized with a different Ethereum chain configuration.\", \"ETH\");\n }\n }\n\n if (requested.btcNetwork) {\n if (!existing.btcNetwork) {\n failInitialization(\n \"AppKit was already initialized without Bitcoin support. A page that needs Bitcoin must initialize AppKit with Bitcoin first.\",\n \"BTC\",\n );\n }\n\n if (existing.btcNetwork !== requested.btcNetwork) {\n failInitialization(\"AppKit was already initialized with a different Bitcoin network.\", \"BTC\");\n }\n }\n}\n","import type { Config } from \"wagmi\";\n\nimport {\n failInitialization,\n getAppKitModal,\n getAppKitState,\n registerManualAppKitConfig,\n} from \"@/core/wallets/appkit/state\";\n\nconst ETHEREUM_CAPABILITY = \"Ethereum\";\nconst SHARED_WAGMI_REPLACEMENT_WARNING =\n \"Shared wagmi config is being replaced. This might indicate multiple initializations.\";\n\n/**\n * Shared wagmi config singleton\n *\n * This allows the AppKitProvider (class-based) to access the wagmi config\n * that's provided by the application-level WagmiProvider.\n *\n * Use `initializeAppKitModal` for canonical initialization. Use\n * `setSharedWagmiConfig` only when another owner initializes AppKit. Do not\n * combine these modes on the same page. `AppKitProvider` reads either mode\n * through `getSharedWagmiConfig`.\n */\n\nlet sharedWagmiConfig: Config | null = null;\n\nexport function setSharedWagmiConfig(config: Config): void {\n registerManualAppKitConfig(ETHEREUM_CAPABILITY);\n\n if (sharedWagmiConfig && sharedWagmiConfig !== config) {\n console.warn(SHARED_WAGMI_REPLACEMENT_WARNING);\n }\n sharedWagmiConfig = config;\n}\n\nexport function getSharedWagmiConfig(): Config {\n const initializedState = getAppKitState();\n if (initializedState) {\n if (!initializedState.wagmiConfig) {\n failInitialization(\n \"AppKit was initialized without Ethereum support. Initialize it with Ethereum support.\",\n \"ETH\",\n );\n }\n\n return initializedState.wagmiConfig;\n }\n\n if (!sharedWagmiConfig) {\n throw new Error(\n \"Shared wagmi config not initialized. \" +\n \"Initialize AppKit with Ethereum support, or use setSharedWagmiConfig() as an exclusive manual alternative.\",\n );\n }\n return sharedWagmiConfig;\n}\n\nexport function hasSharedWagmiConfig(): boolean {\n const initializedState = getAppKitState();\n return initializedState ? initializedState.wagmiConfig !== undefined : sharedWagmiConfig !== null;\n}\n\nexport function ethDisconnectWouldDropBitcoin(): boolean {\n const modal = getAppKitModal();\n const providerType = modal?.getProviderType(\"eip155\");\n return providerType === \"WALLET_CONNECT\" && modal?.getAccount(\"bip122\")?.isConnected === true;\n}\n","import { parseEther } from \"viem\";\nimport {\n connect,\n getAccount,\n getTransactionCount,\n disconnect as wagmiDisconnect,\n estimateGas as wagmiEstimateGas,\n getBalance as wagmiGetBalance,\n sendTransaction as wagmiSendTransaction,\n signMessage as wagmiSignMessage,\n signTypedData as wagmiSignTypedData,\n switchChain as wagmiSwitchChain,\n watchAccount,\n watchChainId,\n} from \"wagmi/actions\";\nimport { walletConnect } from \"wagmi/connectors\";\n\nimport type {\n DisconnectScope,\n ETHConfig,\n ETHTransactionRequest,\n ETHTypedData,\n IETHProvider,\n NetworkInfo,\n} from \"@/core/types\";\nimport { APPKIT_OPEN_EVENT } from \"@/core/wallets/appkit/constants\";\n// Read the modal from the shared singleton rather than from `appKitModal`,\n// which pulls the Bitcoin adapter in with it.\nimport { getAppKitModal } from \"@/core/wallets/appkit/state\";\nimport { ERROR_CODES, WalletError } from \"@/error\";\n\nimport { ethDisconnectWouldDropBitcoin, getSharedWagmiConfig, hasSharedWagmiConfig } from \"./sharedConfig\";\n\n// Grace period after modal close before rejecting as cancelled, to allow\n// async handoffs (WalletConnect deep-link, mobile wallet return) to publish\n// the connected account via watchAccount before we treat the close as a cancel.\nconst MODAL_CLOSE_CANCEL_GRACE_MS = 1500;\nconst WALLET_NOT_CONNECTED_ERROR_MESSAGE = \"Wallet not connected\";\n\n// Generic Ethereum logo, used only when the active wagmi connector does not\n// expose its own name/icon (e.g. some WalletConnect sessions).\nconst ETH_FALLBACK_PROVIDER_NAME = \"Ethereum Wallet\";\nconst ETH_FALLBACK_PROVIDER_ICON =\n \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=\";\n\n/**\n * AppKitProvider - ETH wallet provider using AppKit/Wagmi\n *\n * This provider integrates with Reown's AppKit to provide:\n * - Connection to 600+ ETH wallets (MetaMask, Rainbow, WalletConnect, etc.)\n * - Message signing (personal_sign)\n * - Typed data signing (eth_signTypedData_v4)\n * - Transaction sending and gas estimation\n * - Network switching and information\n *\n * IMPORTANT: Requires shared wagmi config to be set via initializeAppKitModal()\n * before this provider is instantiated. This ensures single wagmi instance.\n */\nexport class AppKitProvider implements IETHProvider {\n private config: ETHConfig;\n private address?: string;\n private chainId?: number;\n private eventHandlers: Map<string, Set<(...args: any[]) => void>> = new Map();\n private unwatchFunctions: (() => void)[] = [];\n\n constructor(config: ETHConfig) {\n this.config = config;\n this.ensureEventWatchers();\n }\n\n /**\n * Attach the wagmi watchers exactly once, and only when the shared config\n * exists. The provider is now constructed unconditionally (it no longer\n * waits on an injected `window.ethereum`), so construction must not throw\n * when AppKit init has not run or has fallen back — that would take down the\n * BTC connector alongside the ETH one. `connectWallet` re-checks and still\n * surfaces the actionable \"AppKit ETH not initialized\" error, and calling\n * this again there picks the watchers up if init landed late.\n */\n private ensureEventWatchers(): void {\n if (this.unwatchFunctions.length > 0) return;\n if (!hasSharedWagmiConfig()) return;\n this.setupEventWatchers();\n }\n\n /**\n * Get the shared wagmi config (throws if not set)\n * This ensures we never create multiple wagmi instances\n */\n private getWagmiConfig() {\n if (!hasSharedWagmiConfig()) {\n throw new Error(\n \"AppKit ETH not initialized. Ensure AppKit modal is initialized at application startup \" +\n \"by calling initializeAppKitModal() with eth config in your app's entry point.\",\n );\n }\n return getSharedWagmiConfig();\n }\n\n private setupEventWatchers(): void {\n const config = this.getWagmiConfig();\n\n // Check for existing connection on initialization (for auto-reconnection)\n const initialAccount = getAccount(config);\n if (initialAccount.address && initialAccount.status === \"connected\") {\n this.address = initialAccount.address;\n this.chainId = initialAccount.chainId;\n // Emit connect event after a short delay to ensure provider is fully initialized\n setTimeout(() => {\n this.emit(\"accountsChanged\", [initialAccount.address!]);\n }, 100);\n }\n\n // Watch for account changes\n const unwatchAccount = watchAccount(config, {\n onChange: (account) => {\n const previousAddress = this.address;\n this.address = account.address;\n this.chainId = account.chainId;\n\n if (previousAddress !== account.address) {\n this.emit(\"accountsChanged\", account.address ? [account.address] : []);\n }\n },\n });\n\n const unwatchChain = watchChainId(config, {\n onChange: (chainId) => {\n const previousChainId = this.chainId;\n this.chainId = chainId;\n\n if (previousChainId !== chainId) {\n this.emit(\"chainChanged\", `0x${chainId.toString(16)}`);\n }\n },\n });\n\n this.unwatchFunctions.push(unwatchAccount, unwatchChain);\n }\n\n private emit(eventName: string, data?: any): void {\n const handlers = this.eventHandlers.get(eventName);\n if (handlers) {\n handlers.forEach((handler) => handler(data));\n }\n }\n\n async connectWallet(): Promise<void> {\n try {\n const config = this.getWagmiConfig();\n // Init may have completed after this provider was constructed.\n this.ensureEventWatchers();\n\n // First check if already connected (from previous session)\n const currentAccount = getAccount(config);\n if (currentAccount.address) {\n this.address = currentAccount.address;\n this.chainId = currentAccount.chainId;\n return;\n }\n\n // Open AppKit modal for manual connection\n if (typeof window !== \"undefined\") {\n const waitForConnection = new Promise<void>((resolve, reject) => {\n let modalHasOpened = false;\n let pendingCancellation: ReturnType<typeof setTimeout> | undefined;\n\n const cleanup = () => {\n clearTimeout(timeout);\n if (pendingCancellation) clearTimeout(pendingCancellation);\n unwatch();\n unsubscribeModal?.();\n };\n\n const timeout = setTimeout(() => {\n cleanup();\n reject(new Error(\"Connection timeout\"));\n }, 60000);\n\n const unwatch = watchAccount(config, {\n onChange: (account) => {\n if (account.address) {\n this.address = account.address;\n this.chainId = account.chainId;\n cleanup();\n resolve();\n }\n },\n });\n\n const modal = getAppKitModal();\n const unsubscribeModal = modal?.subscribeState((state) => {\n if (state.open) {\n modalHasOpened = true;\n if (pendingCancellation) {\n clearTimeout(pendingCancellation);\n pendingCancellation = undefined;\n }\n } else if (modalHasOpened) {\n const currentAccount = getAccount(config);\n if (currentAccount.address) {\n this.address = currentAccount.address;\n this.chainId = currentAccount.chainId;\n cleanup();\n resolve();\n return;\n }\n // Defer rejection so async handoffs (WalletConnect deep-link) can\n // still publish the connected account before we treat the close as a cancel.\n pendingCancellation = setTimeout(() => {\n const latestAccount = getAccount(config);\n if (latestAccount.address) {\n this.address = latestAccount.address;\n this.chainId = latestAccount.chainId;\n cleanup();\n resolve();\n } else {\n cleanup();\n reject(new Error(\"Connection cancelled\"));\n }\n }, MODAL_CLOSE_CANCEL_GRACE_MS);\n }\n });\n\n window.dispatchEvent(new CustomEvent(APPKIT_OPEN_EVENT));\n });\n\n await waitForConnection;\n return;\n }\n\n // Fallback to direct WalletConnect connection if event system not available\n const projectId = process.env.NEXT_PUBLIC_REOWN_PROJECT_ID;\n if (!projectId) {\n throw new Error(\"NEXT_PUBLIC_REOWN_PROJECT_ID environment variable is required\");\n }\n\n const wcConnector = walletConnect({\n projectId,\n metadata: {\n name: \"Babylon Vault\",\n description: \"\",\n url: \"\",\n icons: [\"\"],\n },\n });\n\n const result = await connect(config, { connector: wcConnector });\n this.address = result.accounts[0];\n this.chainId = result.chainId;\n } catch (error) {\n console.error(\"Failed to connect wallet:\", error instanceof Error ? error.message : \"Unknown error\");\n throw new Error(`Failed to connect wallet: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n }\n }\n\n async disconnect(scope: DisconnectScope): Promise<void> {\n if (scope === \"chain\" && ethDisconnectWouldDropBitcoin()) {\n throw new WalletError({\n code: ERROR_CODES.SHARED_SESSION_DISCONNECT_REFUSED,\n message:\n \"Ethereum and Bitcoin share one wallet session. Disconnecting Ethereum alone would also disconnect Bitcoin. Disconnect all wallets instead.\",\n wallet: \"AppKit\",\n chainId: \"ETH\",\n });\n }\n if (scope !== \"local\") await wagmiDisconnect(this.getWagmiConfig());\n this.address = undefined;\n this.chainId = undefined;\n }\n\n async getAddress(): Promise<string> {\n const config = this.getWagmiConfig();\n const account = getAccount(config);\n if (account.address) {\n this.address = account.address;\n this.chainId = account.chainId;\n return this.address;\n }\n\n if (this.address) {\n return this.address;\n }\n\n throw new Error(WALLET_NOT_CONNECTED_ERROR_MESSAGE);\n }\n\n async getPublicKeyHex(): Promise<string> {\n // ETH doesn't expose public keys directly like BTC\n // We return the address as the public identifier\n return this.getAddress();\n }\n\n async signMessage(message: string): Promise<string> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const signature = await wagmiSignMessage(config, {\n message,\n account: address as `0x${string}`,\n });\n return signature;\n } catch (error) {\n throw new Error(`Failed to sign message: ${error}`);\n }\n }\n\n async signTypedData(typedData: ETHTypedData): Promise<string> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const signature = await wagmiSignTypedData(config, {\n account: address as `0x${string}`,\n domain: {\n ...typedData.domain,\n salt: typedData.domain.salt as `0x${string}` | undefined,\n verifyingContract: typedData.domain.verifyingContract as `0x${string}` | undefined,\n },\n types: typedData.types,\n primaryType: typedData.primaryType,\n message: typedData.message,\n });\n return signature;\n } catch (error) {\n throw new Error(`Failed to sign typed data: ${error}`);\n }\n }\n\n async sendTransaction(tx: ETHTransactionRequest): Promise<string> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const hash = await wagmiSendTransaction(config, {\n account: address as `0x${string}`,\n to: tx.to as `0x${string}`,\n value: tx.value ? parseEther(tx.value) : undefined,\n data: tx.data as `0x${string}` | undefined,\n gas: tx.gasLimit,\n maxFeePerGas: tx.maxFeePerGas,\n maxPriorityFeePerGas: tx.maxPriorityFeePerGas,\n nonce: tx.nonce,\n });\n return hash;\n } catch (error) {\n throw new Error(`Failed to send transaction: ${error}`);\n }\n }\n\n async estimateGas(tx: ETHTransactionRequest): Promise<bigint> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const gas = await wagmiEstimateGas(config, {\n account: address as `0x${string}`,\n to: tx.to as `0x${string}`,\n value: tx.value ? parseEther(tx.value) : undefined,\n data: tx.data as `0x${string}` | undefined,\n });\n return gas;\n } catch (error) {\n throw new Error(`Failed to estimate gas: ${error}`);\n }\n }\n\n async getChainId(): Promise<number> {\n if (this.chainId) {\n return this.chainId;\n }\n\n const config = this.getWagmiConfig();\n const account = getAccount(config);\n if (account.chainId) {\n this.chainId = account.chainId;\n return this.chainId;\n }\n\n throw new Error(WALLET_NOT_CONNECTED_ERROR_MESSAGE);\n }\n\n async switchChain(chainId: number): Promise<void> {\n try {\n const config = this.getWagmiConfig();\n // Only allow switching to supported chains\n const supportedChains = [1, 11155111, 31337]; // Mainnet, Sepolia, and Anvil\n if (!supportedChains.includes(chainId)) {\n throw new Error(`Unsupported chain ID: ${chainId}`);\n }\n\n await wagmiSwitchChain(config, { chainId: chainId as 1 | 11155111 | 31337 });\n this.chainId = chainId;\n } catch (error) {\n throw new Error(`Failed to switch chain: ${error}`);\n }\n }\n\n async getBalance(): Promise<bigint> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const balance = await wagmiGetBalance(config, {\n address: address as `0x${string}`,\n });\n return balance.value;\n } catch (error) {\n throw new Error(`Failed to get balance: ${error}`);\n }\n }\n\n async getNonce(): Promise<number> {\n try {\n const config = this.getWagmiConfig();\n const address = await this.getAddress();\n const nonce = await getTransactionCount(config, {\n address: address as `0x${string}`,\n });\n return nonce;\n } catch (error) {\n throw new Error(`Failed to get nonce: ${error}`);\n }\n }\n\n async getNetworkInfo(): Promise<NetworkInfo> {\n const chainId = await this.getChainId();\n return {\n name: this.config.chainName || \"Ethereum\",\n chainId: chainId.toString(),\n };\n }\n\n /**\n * Identity of the wallet the user actually connected through AppKit\n * (e.g. MetaMask, Rainbow), read from the active wagmi connector. Falls back\n * to a generic Ethereum identity when the connector doesn't expose its own.\n */\n private getActiveConnectorIdentity(): { name?: string; icon?: string } | undefined {\n // AppKit tracks the actual wallet the user connected (MetaMask, Rainbow, ...)\n // per chain namespace. The underlying wagmi connector usually reports a\n // generic \"WalletConnect\"/\"Injected\" identity, so prefer AppKit's view.\n const walletInfo = getAppKitModal()?.getWalletInfo(\"eip155\");\n if (walletInfo?.name || walletInfo?.icon) {\n return { name: walletInfo.name, icon: walletInfo.icon };\n }\n\n if (!hasSharedWagmiConfig()) return undefined;\n\n try {\n const { connector } = getAccount(this.getWagmiConfig());\n if (!connector) return undefined;\n\n return { name: connector.name, icon: connector.icon };\n } catch {\n return undefined;\n }\n }\n\n getWalletProviderName(): string {\n const name = this.getActiveConnectorIdentity()?.name;\n return name?.trim() ? name : ETH_FALLBACK_PROVIDER_NAME;\n }\n\n getWalletProviderIcon(): string {\n const icon = this.getActiveConnectorIdentity()?.icon;\n return icon?.trim() ? icon : ETH_FALLBACK_PROVIDER_ICON;\n }\n\n on(eventName: string, handler: (...args: any[]) => void): void {\n if (!this.eventHandlers.has(eventName)) {\n this.eventHandlers.set(eventName, new Set());\n }\n this.eventHandlers.get(eventName)!.add(handler);\n }\n\n off(eventName: string, handler: (...args: any[]) => void): void {\n const handlers = this.eventHandlers.get(eventName);\n if (handlers) {\n handlers.delete(handler);\n }\n }\n\n // Cleanup method for proper resource management\n destroy(): void {\n this.unwatchFunctions.forEach((unwatch) => unwatch());\n this.eventHandlers.clear();\n }\n}\n","import type { ETHConfig, IETHProvider, WalletMetadata } from \"@/core/types\";\nimport { Network } from \"@/core/types\";\nimport { APPKIT_ETH_CONNECTOR_ID } from \"@/core/wallets/appkit/constants\";\n\nimport { AppKitProvider } from \"./provider\";\n\nconst WALLET_PROVIDER_NAME = \"AppKit\";\n\nexport { APPKIT_ETH_CONNECTOR_ID };\n\n/**\n * AppKit wallet metadata for ETH chain\n *\n * Provides connection to 600+ Ethereum wallets through Reown's AppKit:\n * - MetaMask, Rainbow, WalletConnect, Coinbase Wallet, Trust Wallet, etc.\n * - Browser extension wallets (EIP-6963)\n * - Mobile wallets via WalletConnect\n * - Hardware wallets (Ledger, Trezor)\n */\nconst metadata: WalletMetadata<IETHProvider, ETHConfig> = {\n id: APPKIT_ETH_CONNECTOR_ID,\n name: WALLET_PROVIDER_NAME,\n icon: \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=\",\n docs: \"https://docs.reown.com/appkit/overview\",\n // No `wallet` global: AppKit reaches wallets through its own EIP-6963,\n // WalletConnect and hardware transports, none of which require an injected\n // `window.ethereum`. Gating on that global made every user without an EVM\n // browser extension (Safari, WalletConnect-QR, hardware-only) fail with\n // \"Provider not found\" before the AppKit modal could open — and ETH is a\n // required chain for deposit. Mirrors the BTC AppKit entry.\n wallet: undefined,\n createProvider: (_wallet: any, config: ETHConfig) => new AppKitProvider(config),\n networks: [\n Network.MAINNET, // ETH mainnet (chainId: 1)\n Network.TESTNET, // ETH testnet (chainId: 11155111 - Sepolia)\n Network.SIGNET, // Also allow SIGNET/devnet/localhost environments\n ],\n label: \"Connect ETH Wallet\",\n};\n\nexport default metadata;\n","export default \"data:image/svg+xml,%3csvg%20enable-background='new%200%200%201920%201920'%20viewBox='0%200%201920%201920'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='m959.8%2080.7-539.7%20895.6%20539.7-245.3z'%20fill='%238a92b2'/%3e%3cpath%20d='m959.8%20731-539.7%20245.3%20539.7%20319.1z'%20fill='%2362688f'/%3e%3cpath%20d='m1499.6%20976.3-539.8-895.6v650.3z'%20fill='%2362688f'/%3e%3cpath%20d='m959.8%201295.4%20539.8-319.1-539.8-245.3z'%20fill='%23454a75'/%3e%3cpath%20d='m420.1%201078.7%20539.7%20760.6v-441.7z'%20fill='%238a92b2'/%3e%3cpath%20d='m959.8%201397.6v441.7l540.1-760.6z'%20fill='%2362688f'/%3e%3c/svg%3e\"","import type { ChainMetadata, ETHConfig, IETHProvider } from \"@/core/types\";\n\nimport appkit from \"./appkit\";\nimport icon from \"./icon.svg\";\n\n/**\n * Ethereum chain metadata\n *\n * Defines the ETH chain configuration with available wallet providers.\n * Currently supports AppKit for connection to 600+ Ethereum wallets.\n */\nconst metadata: ChainMetadata<\"ETH\", IETHProvider, ETHConfig> = {\n chain: \"ETH\",\n name: \"Ethereum\",\n // icon: \"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPgogIDxwYXRoIGQ9Ik0xNiA0TDcuNSAxNi4yNUwxNiAyMkwyNC41IDE2LjI1TDE2IDR6IiBmaWxsPSJ3aGl0ZSIvPgogIDxwYXRoIGQ9Ik0xNiAyMi43NUw3LjUgMTdMMTYgMjhMMjQuNSAxN0wxNiAyMi43NXoiIGZpbGw9IndoaXRlIiBmaWxsLW9wYWNpdHk9IjAuNiIvPgo8L3N2Zz4=\",\n icon,\n wallets: [appkit],\n};\n\nexport default metadata;\n","import { WagmiAdapter } from \"@reown/appkit-adapter-wagmi\";\nimport { createAppKit, modal as reownAppKitModal } from \"@reown/appkit/react\";\nimport { http, type Chain } from \"viem\";\nimport { cookieStorage, createStorage } from \"wagmi\";\nimport { baseAccount } from \"wagmi/connectors\";\n\nimport {\n assertAppKitCapabilities,\n createAppKitCapabilities,\n failInitialization,\n getAppKitState,\n setAppKitState,\n validateAppKitInitialization,\n} from \"@/core/wallets/appkit/state\";\n\nimport { getSharedWagmiConfig } from \"./sharedConfig\";\n\nexport interface AppKitMetadata {\n name: string;\n description: string;\n url: string;\n icons: string[];\n}\n\nexport interface AppKitModalConfig {\n projectId?: string;\n metadata: AppKitMetadata;\n eth: {\n /** ETH network chain configuration, from the host application's network config. */\n chain: Chain;\n };\n}\n\n/**\n * Builds the Ethereum adapter.\n *\n * The unified (ETH+BTC) initializer calls this too, so the Ethereum half of\n * AppKit is set up in exactly one place regardless of which entry point the\n * host imported.\n */\nexport function createETHWagmiAdapter(chain: Chain, projectId: string): WagmiAdapter {\n // Pin the transport to the chain's configured RPC URL. Without this, wagmi\n // falls back to viem's bundled public RPC (e.g. sepolia.drpc.org) which\n // doesn't see contracts on private/devnet deployments.\n const ethRpcUrl = chain.rpcUrls.default.http[0];\n // Supply the Base Account connector ourselves so AppKit skips constructing\n // its own default one. Its default enables the Base Account SDK's telemetry,\n // which injects an inline analytics script into the page.\n const adapter = new WagmiAdapter({\n networks: [chain],\n projectId,\n ssr: false,\n storage: createStorage({ storage: cookieStorage }),\n connectors: [baseAccount({ preference: { telemetry: false } })],\n transports: {\n [chain.id]: http(ethRpcUrl),\n },\n });\n\n return adapter;\n}\n\n/**\n * Initializes an Ethereum-only AppKit instance. Imports no Bitcoin adapter and\n * no Bitcoin network definitions, so it is safe to reach from the `./eth`\n * entry point.\n */\nexport function initializeAppKitModal(config: AppKitModalConfig) {\n if (!validateAppKitInitialization(config.projectId)) return null;\n\n const { chain } = config.eth;\n const capabilities = createAppKitCapabilities({\n projectId: config.projectId,\n metadata: config.metadata,\n ethChain: chain,\n });\n const existingState = getAppKitState();\n\n if (existingState) {\n assertAppKitCapabilities(existingState, capabilities);\n return { modal: existingState.modal, wagmiConfig: getSharedWagmiConfig() };\n }\n\n if (reownAppKitModal)\n failInitialization(\"Reown AppKit was initialized outside this package. Use only this package to initialize it.\");\n\n const wagmiAdapter = createETHWagmiAdapter(chain, config.projectId);\n\n const modal = createAppKit({\n adapters: [wagmiAdapter],\n networks: [chain],\n projectId: config.projectId,\n metadata: config.metadata,\n });\n const initializedState = setAppKitState({ modal, ...capabilities, wagmiConfig: wagmiAdapter.wagmiConfig });\n\n return { modal: initializedState.modal, wagmiConfig: wagmiAdapter.wagmiConfig };\n}\n","import { useEffect } from \"react\";\n\nimport { APPKIT_OPEN_EVENT } from \"@/core/wallets/appkit/constants\";\n// Read the modal from the shared singleton rather than from `appKitModal`,\n// which pulls the Bitcoin adapter in with it and would put Bitcoin code in the\n// `./eth` graph.\nimport { getAppKitModal } from \"@/core/wallets/appkit/state\";\n\n/**\n * Unified AppKit modal open listener\n *\n * Listens for AppKit open events and opens the unified AppKit modal.\n * Both ETH and BTC connectors dispatch the same event to open the modal.\n *\n * If AppKit modal is not initialized, the hook will silently ignore open requests.\n */\nexport const useAppKitOpenListener = () => {\n useEffect(() => {\n const handleOpenRequest = () => {\n try {\n const modal = getAppKitModal();\n\n if (modal) {\n modal.open();\n }\n } catch (error) {\n // AppKit not initialized or not available - log warning for diagnostics\n console.warn(\"AppKit modal not available:\", error);\n }\n };\n\n window.addEventListener(APPKIT_OPEN_EVENT, handleOpenRequest);\n return () => window.removeEventListener(APPKIT_OPEN_EVENT, handleOpenRequest);\n }, []);\n};\n","import { type Connectors, useChainProviders } from \"@/context/Chain.context\";\n\nexport type SupportedChains = keyof Connectors;\n\nexport function useChainConnector<K extends SupportedChains>(chainId: K) {\n const connectors = useChainProviders();\n\n return connectors?.[chainId] ?? null;\n}\n","import okxLogo from \"./icons/okx.svg\";\nimport { MONOCHROME_MARK_BACKGROUND } from \"./constants\";\n\n/**\n * AppKit reports the connected ETH wallet's own name and icon, and for wallets\n * we also support on Bitcoin that artwork differs from the asset we ship — OKX\n * returns a square tile where our Bitcoin asset is the circular mark, so one\n * wallet reads as two in the connected-wallet menu. Prefer our own asset for\n * those, keyed by name because that is the only identity AppKit exposes.\n */\nconst FIRST_PARTY_ICONS: { match: RegExp; icon: string; iconBackground?: string }[] = [\n { match: /okx/i, icon: okxLogo, iconBackground: MONOCHROME_MARK_BACKGROUND },\n];\n\nexport function resolveFirstPartyIcon(walletName: string) {\n return FIRST_PARTY_ICONS.find(({ match }) => match.test(walletName));\n}\n","import { useContext } from \"react\";\n\nimport { StateContext } from \"@/context/State.context\";\n\nexport const useWidgetState = () => useContext(StateContext);\n","import { useCallback, useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useChainProviders } from \"@/context/Chain.context\";\nimport { useLifeCycleHooks } from \"@/context/LifecycleHooks.context\";\nimport {\n confirmedChains,\n isConfirmationReceiptCovered,\n isLiveConfirmationReceiptValid,\n isValidConfirmationReceipt,\n subscribeToConfirmationIdentityChanges,\n WALLET_CONFIRMATION_RECEIPT_KEY,\n} from \"@/core/confirmationReceipt\";\nimport { ChainId, HashMap, IChain, IConnector, IETHProvider, IWallet, Network } from \"@/core/types\";\nimport { resolveFirstPartyIcon } from \"@/core/wallets/firstPartyIcons\";\nimport { ERROR_CODES, isSharedSessionRefusal, WalletError } from \"@/error\";\n\nimport { useWidgetState } from \"./useWidgetState\";\n\n/**\n * AppKit exposes a single generic \"Ethereum\" wallet entry, so the connected\n * wallet's static metadata carries a generic chain icon/name rather than the\n * actual wallet the user picked (MetaMask, Rainbow, ...). Re-resolve the\n * display identity from the provider, which reads it off the live wagmi\n * connector, so the selected-wallet UI shows the real wallet.\n */\nasync function resolveEthDisplayWallet(wallet: IWallet): Promise<IWallet> {\n const provider = wallet.provider as IETHProvider | null;\n if (!provider?.getWalletProviderName || !provider?.getWalletProviderIcon) return wallet;\n\n const [name, icon] = await Promise.all([provider.getWalletProviderName(), provider.getWalletProviderIcon()]);\n const firstParty = resolveFirstPartyIcon(name || wallet.name);\n\n return {\n id: wallet.id,\n name: name || wallet.name,\n icon: firstParty?.icon || icon || wallet.icon,\n iconBackground: firstParty?.iconBackground,\n docs: wallet.docs,\n installed: wallet.installed,\n provider: wallet.provider,\n account: wallet.account,\n label: wallet.label,\n hardware: wallet.hardware,\n };\n}\n\n/**\n * Connection-time WalletError codes that the user must see in-dialog —\n * silently bouncing back to chain selection would leave the user with no\n * idea why their wallet didn't connect.\n */\nconst TERMINAL_CONNECT_ERROR_CODES: ReadonlySet<string> = new Set([ERROR_CODES.INCOMPATIBLE_WALLET_VERSION]);\n\nexport interface BTCAddressValidation {\n validateAddress(network: Network, address: string): void;\n validateAddressWithPK(address: string, publicKey: string, network: Network): boolean;\n}\n\ninterface Props {\n persistent: boolean;\n accountStorage: HashMap;\n onError?: (e: Error) => void;\n btcValidation?: BTCAddressValidation;\n}\n\nexport function useWalletConnectors({ persistent, accountStorage, onError, btcValidation }: Props) {\n const connectors = useChainProviders();\n const {\n confirmed,\n confirmationReceipt,\n visible,\n selectWallet,\n removeWallet,\n displayLoader,\n displayChains,\n displayError,\n confirm,\n unconfirm,\n requiredChainIds = [],\n } = useWidgetState();\n const { verifyBTCAddress } = useLifeCycleHooks();\n const validationGenerationRef = useRef(0);\n const previousRequiredChainIdsRef = useRef(requiredChainIds);\n const confirmationCandidate =\n confirmationReceipt ?? (persistent && !visible ? accountStorage.get(WALLET_CONFIRMATION_RECEIPT_KEY) : undefined);\n const confirmationCandidateRef = useRef<string>();\n const dirtyOptionalChainsRef = useRef<Set<ChainId>>(new Set());\n const requiredConnectorsReady = requiredChainIds.every((chainId) => connectors[chainId as ChainId]?.connectedWallet);\n\n // A wallet that failed post-connect validation is forgotten locally no matter\n // what the provider does: the chain disconnect is attempted first so an\n // AppKit wallet is released, and a refusal (shared session) or a failure\n // falls back to the local teardown so the wallet cannot be selected again.\n const droppingRef = useRef<Set<string>>(new Set());\n const dropRejectedWallet = async (connector: Pick<IConnector, \"id\" | \"disconnect\">) => {\n droppingRef.current.add(connector.id);\n removeWallet?.(connector.id);\n if (persistent) accountStorage.delete(connector.id);\n try {\n await connector.disconnect(\"chain\");\n } catch (error) {\n if (!isSharedSessionRefusal(error)) {\n console.error(\n \"Failed to disconnect rejected wallet:\",\n error instanceof Error ? error.message : \"Unknown error\",\n );\n }\n await connector.disconnect(\"local\");\n } finally {\n droppingRef.current.delete(connector.id);\n }\n };\n\n // Connecting event\n useEffect(() => {\n if (!visible) return;\n\n const connectorArr = Object.values(connectors);\n\n const unsubscribeArr = connectorArr.filter(Boolean).map((connector) =>\n connector.on(\"connecting\", (message?: string, description?: string) => {\n displayLoader?.(message, description);\n }),\n );\n\n return () => unsubscribeArr.forEach((unsubscribe) => unsubscribe());\n }, [visible, displayLoader, connectors]);\n\n // Connect Event\n useEffect(() => {\n const connectorArr = Object.values(connectors).filter(Boolean);\n\n const handlers: Record<string, (connector: any) => (connectedWallet: IWallet) => void> = {\n BTC: (connector) => async (connectedWallet) => {\n try {\n if (!connectedWallet || !connectedWallet.account) return;\n if (!btcValidation) throw new Error(\"Bitcoin address validation is unavailable\");\n\n selectWallet?.(\"BTC\", connectedWallet);\n\n if (persistent && connectedWallet.account?.address) {\n accountStorage.set(connector.id, connectedWallet.id);\n }\n\n if (!visible) return;\n\n btcValidation.validateAddress(connector.config.network, connectedWallet.account.address);\n\n const goToNextScreen = () => void displayChains?.();\n\n if (\n !btcValidation.validateAddressWithPK(\n connectedWallet.account?.address ?? \"\",\n connectedWallet.account?.publicKeyHex ?? \"\",\n connector.config.network,\n )\n ) {\n displayError?.({\n title: \"Public Key Mismatch\",\n description:\n \"The Bitcoin address and Public Key for this wallet do not match. Please contact your wallet provider for support.\",\n onSubmit: goToNextScreen,\n onCancel: () => {\n void dropRejectedWallet(connector);\n displayChains?.();\n },\n });\n\n return;\n }\n\n if (verifyBTCAddress && !(await verifyBTCAddress(connectedWallet.account?.address ?? \"\"))) {\n displayError?.({\n title: \"Staking Currently Unavailable\",\n description:\n \"Staking is temporarily disabled due to network downtime. New stakes are paused until the network resumes.\",\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: async () => {\n void dropRejectedWallet(connector);\n displayChains?.();\n },\n });\n\n return;\n }\n\n goToNextScreen();\n } catch (e: any) {\n void dropRejectedWallet(connector);\n displayError?.({\n title: \"Connection Failed\",\n description: e.message,\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: async () => {\n displayChains?.();\n },\n });\n }\n },\n BBN: (connector) => (connectedWallet) => {\n if (connectedWallet) {\n selectWallet?.(connector.id, connectedWallet);\n\n if (persistent && connectedWallet.account?.address) {\n accountStorage.set(connector.id, connectedWallet.id);\n }\n }\n\n displayChains?.();\n },\n ETH: (connector) => async (connectedWallet) => {\n if (connectedWallet) {\n selectWallet?.(connector.id, await resolveEthDisplayWallet(connectedWallet));\n\n if (persistent && connectedWallet.account?.address) {\n accountStorage.set(connector.id, connectedWallet.id);\n }\n }\n\n displayChains?.();\n },\n };\n\n const unsubscribeArr = connectorArr.map((connector) =>\n connector.on(\"connect\", handlers[connector.id]?.(connector)),\n );\n\n connectorArr.forEach((connector) => {\n const connectedWallet = droppingRef.current.has(connector.id) ? null : connector.connectedWallet;\n if (connector.id === \"ETH\" && connectedWallet) {\n void resolveEthDisplayWallet(connectedWallet).then((wallet) => selectWallet?.(connector.id, wallet));\n return;\n }\n selectWallet?.(connector.id, connectedWallet);\n });\n\n return () => unsubscribeArr.forEach((unsubscribe) => unsubscribe());\n }, [\n onError,\n selectWallet,\n removeWallet,\n displayChains,\n displayError,\n verifyBTCAddress,\n btcValidation,\n accountStorage,\n connectors,\n persistent,\n visible,\n ]);\n\n // Disconnect Event\n useLayoutEffect(() => {\n const connectorArr = Object.values(connectors);\n\n const unsubscribeArr = connectorArr.filter(Boolean).map((connector) =>\n connector.on(\"disconnect\", (connectedWallet: IWallet) => {\n if (connectedWallet) {\n // Losing a required chain invalidates the confirmation it was part\n // of, so the receipt must not survive to auto-confirm a later\n // reconnect. An optional chain leaving is not a consent change.\n if (requiredChainIds.includes(connector.id)) {\n validationGenerationRef.current += 1;\n accountStorage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n }\n removeWallet?.(connector.id);\n displayChains?.();\n if (persistent) {\n accountStorage.delete(connector.id);\n }\n }\n }),\n );\n\n return () => unsubscribeArr.forEach((unsubscribe) => unsubscribe());\n }, [removeWallet, displayChains, connectors, persistent, accountStorage, requiredChainIds]);\n\n // Error Event\n useEffect(() => {\n const connectorArr = Object.values(connectors);\n\n const unsubscribeArr = connectorArr.filter(Boolean).map((connector) =>\n connector.on(\"error\", (error: Error) => {\n onError?.(error);\n\n // Terminal errors (e.g. the wallet extension is too old) need an\n // in-dialog message so the user can act on them. Anything else\n // falls through to the existing \"bounce back to chains\" behaviour\n // — host apps' `onError` callbacks still get the raw error.\n // Guard on `displayError` directly so we still fall through to\n // `displayChains?.()` below if the dialog state isn't wired up;\n // otherwise the user could be stranded on the current screen.\n if (error instanceof WalletError && TERMINAL_CONNECT_ERROR_CODES.has(error.code) && displayError) {\n const walletName = error.wallet ?? \"your wallet\";\n displayError({\n title: `Update ${walletName}`,\n description: error.message || `${walletName} needs to be updated before you can connect.`,\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: () => {\n displayChains?.();\n },\n });\n return;\n }\n\n displayChains?.();\n }),\n );\n\n return () => unsubscribeArr.forEach((unsubscribe) => unsubscribe());\n }, [onError, displayChains, displayError, connectors]);\n\n const validateConfirmation = useCallback(async () => {\n const generation = ++validationGenerationRef.current;\n if (!confirmationCandidate) return;\n\n if (!confirmationReceipt && !requiredConnectorsReady) return;\n\n const covered = await isLiveConfirmationReceiptValid(confirmationCandidate, requiredChainIds, connectors);\n if (generation !== validationGenerationRef.current) return;\n\n if (!covered) {\n accountStorage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n unconfirm?.();\n return;\n }\n\n if (!confirmed && !visible) {\n confirm?.(confirmationCandidate);\n displayChains?.();\n return;\n }\n\n // Keep the stored receipt alive with its confirmed session.\n if (persistent && confirmed) {\n accountStorage.set(WALLET_CONFIRMATION_RECEIPT_KEY, confirmationCandidate);\n }\n }, [\n accountStorage,\n confirmationCandidate,\n confirmationReceipt,\n confirmed,\n confirm,\n connectors,\n displayChains,\n persistent,\n requiredChainIds,\n requiredConnectorsReady,\n unconfirm,\n visible,\n ]);\n\n useEffect(() => {\n void validateConfirmation();\n }, [validateConfirmation]);\n\n useLayoutEffect(() => {\n const previousCandidate = confirmationCandidateRef.current;\n if (!confirmationCandidate || (previousCandidate && previousCandidate !== confirmationCandidate)) {\n dirtyOptionalChainsRef.current.clear();\n }\n confirmationCandidateRef.current = confirmationCandidate;\n }, [confirmationCandidate]);\n\n useLayoutEffect(() => {\n validationGenerationRef.current += 1;\n const newlyRequiredChainIds = requiredChainIds.filter(\n (chainId) => !previousRequiredChainIdsRef.current.includes(chainId),\n );\n previousRequiredChainIdsRef.current = requiredChainIds;\n if (!confirmationCandidate) return;\n\n const stopWatchingIdentity = subscribeToConfirmationIdentityChanges(\n confirmationCandidate,\n confirmedChains(confirmationCandidate),\n connectors,\n (chain) => {\n if (!requiredChainIds.includes(chain)) {\n dirtyOptionalChainsRef.current.add(chain);\n return;\n }\n\n validationGenerationRef.current += 1;\n accountStorage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n unconfirm?.();\n },\n );\n if (!confirmationReceipt && !requiredConnectorsReady) return stopWatchingIdentity;\n\n if (\n !isConfirmationReceiptCovered(confirmationCandidate, requiredChainIds, connectors) ||\n newlyRequiredChainIds.some((chainId) => dirtyOptionalChainsRef.current.has(chainId as ChainId)) ||\n (confirmationReceipt &&\n newlyRequiredChainIds.length > 0 &&\n !isValidConfirmationReceipt(confirmationCandidate, newlyRequiredChainIds, connectors))\n ) {\n stopWatchingIdentity();\n accountStorage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n unconfirm?.();\n return;\n }\n\n if (confirmationReceipt && newlyRequiredChainIds.length > 0) {\n unconfirm?.(true);\n }\n\n return stopWatchingIdentity;\n }, [\n accountStorage,\n confirmationCandidate,\n confirmationReceipt,\n connectors,\n requiredChainIds,\n requiredConnectorsReady,\n unconfirm,\n ]);\n\n useEffect(\n () => () => {\n validationGenerationRef.current += 1;\n },\n [],\n );\n\n const connect = useCallback(\n async (chain: IChain, wallet: IWallet) => {\n const connector = connectors[chain.id as keyof typeof connectors];\n await connector?.connect(wallet.id);\n },\n [connectors],\n );\n\n return { connect };\n}\n","import { useCallback, useMemo } from \"react\";\n\nimport { createExternalWallet } from \"@/core\";\nimport { ExternalConnector } from \"@/core/types\";\n\nexport function useWalletWidgets(connectors: any, config: any, onError?: (e: Error) => void) {\n const createChainWidget = useCallback(\n (chainId: string, externalConnectors: ExternalConnector[]) => (\n <>\n {externalConnectors.map(({ id, widget: Component }) => (\n <Component\n key={id}\n id={id}\n connector={connectors[chainId]}\n createWallet={createExternalWallet}\n onError={onError}\n />\n ))}\n </>\n ),\n [connectors, onError],\n );\n\n return useMemo(\n () =>\n config.reduce(\n (acc: Record<string, JSX.Element>, config: any) => ({\n ...acc,\n [config.chain]: createChainWidget(config.chain, config.connectors ?? []),\n }),\n {},\n ) as Record<string, JSX.Element>,\n [createChainWidget, config],\n );\n}\n","import { useCallback, useMemo } from \"react\";\n\nimport { useChainProviders } from \"@/context/Chain.context\";\nimport type { ChainId } from \"@/core/types\";\nimport { isSharedSessionRefusal } from \"@/error\";\n\nimport { useWidgetState } from \"./useWidgetState\";\n\nexport function useWalletConnect() {\n const {\n confirmed,\n chains: chainMap,\n requiredChainIds,\n selectedWallets,\n open: openModal,\n displayChains,\n displayError,\n displayWallets,\n reset,\n } = useWidgetState();\n const connectors = useChainProviders();\n\n /**\n * Opens the wallet dialog, on one chain's wallet list when given a chain.\n *\n * Deliberately does not `reset()`: attaching an optional chain to a session\n * that is already confirmed must not tear that session down. Requirement-set\n * changes are handled separately — `State.context` drops the confirmation\n * when a new required chain appears.\n */\n const open = useCallback(\n (chain?: ChainId) => {\n // Membership, not truthiness, for the same reason as `disconnect` below:\n // React's bivariant handler types let a consumer write `onClick={open}`,\n // which calls this with a MouseEvent. Testing the key explicitly means\n // that lands on the chain list rather than depending on a lookup miss.\n if (chain !== undefined && Object.prototype.hasOwnProperty.call(chainMap, chain)) {\n displayWallets?.(chain);\n } else {\n displayChains?.();\n }\n openModal?.();\n },\n [chainMap, displayChains, displayWallets, openModal],\n );\n\n /**\n * Disconnects a single chain, or every chain when called without one.\n *\n * A single-chain disconnect the provider refuses (the chain shares its\n * wallet session with another chain) is explained in the dialog and still\n * rejects, so the caller knows nothing was disconnected.\n *\n * Membership is tested rather than truthiness because React's bivariant\n * handler types let `onClick={disconnect}` pass a MouseEvent in here, which\n * must not be mistaken for a chain and silently skip the disconnect-all path.\n */\n const disconnect = useCallback(\n async (chain?: ChainId) => {\n if (chain !== undefined && Object.prototype.hasOwnProperty.call(connectors, chain)) {\n try {\n await connectors[chain]?.disconnect(\"chain\");\n } catch (error) {\n if (isSharedSessionRefusal(error)) {\n displayError?.({\n title: \"Wallets share one session\",\n description: error.message,\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: () => {\n displayChains?.();\n },\n });\n }\n throw error;\n }\n return;\n }\n\n for (const connector of Object.values(connectors)) {\n if (!connector) continue;\n\n await connector.disconnect(\"all\");\n }\n\n reset?.();\n },\n [connectors, displayChains, displayError, reset],\n );\n\n const selected = useMemo(\n () => requiredChainIds.every((chainId) => Boolean(selectedWallets[chainId])),\n [requiredChainIds, selectedWallets],\n );\n\n return {\n selected,\n connected: selected && confirmed,\n open,\n disconnect,\n };\n}\n","import { Avatar, Text } from \"@babylonlabs-io/core-ui\";\nimport type { JSX, PropsWithChildren } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\n\ninterface ChainButtonProps extends PropsWithChildren {\n className?: string;\n logo?: string | JSX.Element;\n title?: string | JSX.Element;\n alt?: string;\n onClick?: () => void;\n}\n\nexport function ChainButton({ className, alt, logo, title, children, onClick }: ChainButtonProps) {\n const avatar = typeof logo === \"string\" ? <Avatar url={logo} alt={alt} /> : <Avatar>{logo}</Avatar>;\n\n const getTestId = () => {\n if (typeof title === \"string\") {\n if (title.includes(\"Bitcoin\")) return \"select-bitcoin-wallet-button\";\n if (title.includes(\"Ethereum\")) return \"select-ethereum-wallet-button\";\n if (title.includes(\"Babylon\")) return \"select-babylon-wallet-button\";\n }\n return \"chain-button\";\n };\n\n return (\n <Text\n as=\"button\"\n className={twMerge(\n \"flex w-full cursor-pointer flex-col gap-4 rounded-lg bg-neutral-200 p-4 text-accent-primary\",\n className,\n )}\n onClick={onClick}\n data-testid={getTestId()}\n >\n <div className=\"flex w-full items-center gap-2.5\">\n <div className=\"flex items-center\">{avatar}</div>\n {title}\n\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n className=\"ml-auto block text-accent-secondary\"\n >\n <path\n d=\"M8.58984 16.59L13.1698 12L8.58984 7.41L9.99984 6L15.9998 12L9.99984 18L8.58984 16.59Z\"\n fill=\"currentColor\"\n />\n </svg>\n </div>\n\n {children && <div className=\"w-full\">{children}</div>}\n </Text>\n );\n}\n","import { CheckIcon, CopyIcon, Text, useCopy, WalletIcon } from \"@babylonlabs-io/core-ui\";\nimport { memo, type KeyboardEvent, type MouseEvent } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\n\ninterface ConnectedWalletProps {\n className?: string;\n logo: string;\n // See `IWallet.iconBackground`.\n logoBackground?: string;\n address: string;\n}\n\n// Addresses longer than this are middle-truncated (keep the head and tail) so\n// the user can verify the start and end at a glance. The full value is always\n// available via the `title` tooltip and the copy button.\nconst ADDRESS_TRUNCATE_THRESHOLD = 36;\nconst ADDRESS_EDGE_CHARS = 14;\n\nfunction truncateAddress(address: string) {\n if (address.length <= ADDRESS_TRUNCATE_THRESHOLD) return address;\n return `${address.slice(0, ADDRESS_EDGE_CHARS)}…${address.slice(-ADDRESS_EDGE_CHARS)}`;\n}\n\nexport const ConnectedWallet = memo(({ className, logo, logoBackground, address }: ConnectedWalletProps) => {\n const { isCopied, copyToClipboard } = useCopy();\n const copied = isCopied(address);\n\n // This row renders inside the clickable chain button, so stop propagation (and\n // use a span rather than a nested <button>) to keep the copy action isolated.\n const handleCopy = (e: MouseEvent | KeyboardEvent) => {\n e.stopPropagation();\n copyToClipboard(address, address);\n };\n\n return (\n <div className={twMerge(\"flex items-center gap-2.5 rounded-lg bg-neutral-200 p-2\", className)}>\n <WalletIcon size=\"small\" className=\"shrink-0\" url={logo} background={logoBackground} />\n\n <Text\n as=\"div\"\n variant=\"caption\"\n title={address}\n className=\"min-w-0 flex-1 truncate text-left font-mono text-accent-secondary\"\n >\n {truncateAddress(address)}\n </Text>\n\n <span\n role=\"button\"\n tabIndex={0}\n aria-label={copied ? \"Address copied\" : \"Copy address\"}\n onClick={handleCopy}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \" \") handleCopy(e);\n }}\n className=\"flex shrink-0 cursor-pointer items-center text-accent-secondary hover:text-accent-primary\"\n >\n {copied ? <CheckIcon size={16} variant=\"success\" /> : <CopyIcon size={16} />}\n </span>\n </div>\n );\n});\n","import { Button, Heading, Text } from \"@babylonlabs-io/core-ui\";\nimport { memo } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\n\nimport { ChainButton } from \"@/components/ChainButton\";\nimport { ConnectedWallet } from \"@/components/ConnectedWallet\";\nimport type { IChain, IWallet } from \"@/core/types\";\n\nconst DISABLED_CONNECT_BG = \"disabled:!bg-[#CCCCCC] dark:disabled:!bg-secondary-strokeDark\";\n\nconst SELECT_WALLET_TITLE_PREFIX = \"Select \";\nconst SELECT_WALLET_TITLE_SUFFIX = \" Wallet\";\nconst OPTIONAL_CHAIN_TITLE_SUFFIX = \" (Optional)\";\n\ninterface ChainsProps {\n disabled?: boolean;\n chains: IChain[];\n /** Chains outside this set are labelled optional. Omit to label none. */\n requiredChainIds?: readonly string[];\n className?: string;\n selectedWallets?: Record<string, IWallet | undefined>;\n onConfirm?: () => void;\n onSelectChain?: (chain: IChain) => void;\n}\n\nexport const Chains = memo(\n ({\n disabled = false,\n chains,\n requiredChainIds,\n selectedWallets = {},\n className,\n onConfirm,\n onSelectChain,\n }: ChainsProps) => (\n <div\n className={twMerge(\n \"flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight text-accent-primary\",\n className,\n )}\n >\n <div className=\"border-b border-secondary-strokeLight p-6\">\n <Heading variant=\"h5\" className=\"text-accent-primary\">\n Connect Wallets\n </Heading>\n </div>\n\n <div className=\"flex flex-col gap-4 p-6\">\n <div className=\"flex flex-col gap-2\">\n {chains.map((chain) => {\n const selectedWallet = selectedWallets[chain.id];\n const optional = requiredChainIds !== undefined && !requiredChainIds.includes(chain.id);\n\n return (\n <ChainButton\n key={chain.id}\n title={`${SELECT_WALLET_TITLE_PREFIX}${chain.name}${SELECT_WALLET_TITLE_SUFFIX}${\n optional ? OPTIONAL_CHAIN_TITLE_SUFFIX : \"\"\n }`}\n logo={chain.icon}\n alt={chain.name}\n onClick={() => void onSelectChain?.(chain)}\n >\n {selectedWallet && (\n <ConnectedWallet\n logo={selectedWallet.icon}\n logoBackground={selectedWallet.iconBackground}\n address={selectedWallet.account?.address ?? \"\"}\n />\n )}\n </ChainButton>\n );\n })}\n\n <Button\n color=\"secondary\"\n disabled={disabled}\n fluid\n onClick={onConfirm}\n className={twMerge(\"text-sm disabled:!opacity-100\", DISABLED_CONNECT_BG)}\n data-testid=\"chains-connect-button\"\n >\n Connect\n </Button>\n </div>\n\n <Text variant=\"body2\" className=\"text-center text-accent-secondary\">\n By clicking Connect you agree with the{\" \"}\n <a\n href=\"https://babylonlabs.io/terms-of-use\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-accent-primary underline\"\n >\n Terms of Use\n </a>{\" \"}\n and{\" \"}\n <a\n href=\"https://babylonlabs.io/privacy-policy\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-accent-primary underline\"\n >\n Privacy Policy\n </a>\n .\n </Text>\n </div>\n </div>\n ),\n);\n","import { useCallback, useMemo } from \"react\";\n\nimport type { IChain } from \"@/core/types\";\n// Connector ids come from the shared constants module, not from each chain's\n// wallet metadata — importing the metadata here would put every Bitcoin wallet\n// adapter into the `./eth` graph, since this screen is part of the dialog.\nimport { useChainProviders } from \"@/context/Chain.context\";\nimport { APPKIT_BTC_CONNECTOR_ID, APPKIT_ETH_CONNECTOR_ID, APPKIT_OPEN_EVENT } from \"@/core/wallets/appkit/constants\";\nimport { ethDisconnectWouldDropBitcoin } from \"@/core/wallets/eth/appkit/sharedConfig\";\nimport { isSharedSessionRefusal } from \"@/error\";\nimport { useWalletConnect } from \"@/hooks/useWalletConnect\";\nimport { useWidgetState } from \"@/hooks/useWidgetState\";\n\nimport { Chains } from \"./index\";\n\n// AppKit's connectWallet() no-ops when the chain is already connected, so an\n// already-connected AppKit row would do nothing on click. Reopening the modal\n// directly lets the user switch accounts or disconnect to pick another wallet.\n// (Switching/disconnecting triggers the vault's reset-both-wallets policy.)\nfunction openAppKitModal() {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(APPKIT_OPEN_EVENT));\n }\n}\n\ninterface ContainerProps {\n className?: string;\n onConfirm?: () => void;\n}\n\nexport function ChainsContainer(props: ContainerProps) {\n const { chains, requiredChainIds, selectedWallets, displayWallets } = useWidgetState();\n const { selected, disconnect } = useWalletConnect();\n const connectors = useChainProviders();\n\n const chainArr = useMemo(() => Object.values(chains), [chains]);\n\n const handleSelectChain = useCallback(\n async (chain: IChain) => {\n if (chain.id === \"ETH\" || chain.id === \"BTC\") {\n const connector = connectors[chain.id];\n const appkitId = chain.id === \"ETH\" ? APPKIT_ETH_CONNECTOR_ID : APPKIT_BTC_CONNECTOR_ID;\n const wallet = connector?.wallets.find((candidate) => candidate.id === appkitId);\n if (wallet && connector?.wallets.length === 1) {\n const connected = Boolean(connector.connectedWallet);\n try {\n if (!connected) {\n await connector.connect(wallet.id);\n } else if (chain.id === \"ETH\" && !ethDisconnectWouldDropBitcoin()) {\n openAppKitModal();\n } else {\n await disconnect(chain.id);\n }\n } catch (error) {\n if (!isSharedSessionRefusal(error)) {\n console.error(\n `Failed to ${connected ? \"disconnect\" : \"connect\"} AppKit ${chain.id}:`,\n error instanceof Error ? error.message : \"Unknown error\",\n );\n }\n }\n return;\n }\n }\n\n // Normal flow for other chains or if chain has multiple wallets\n displayWallets?.(chain.id);\n },\n [displayWallets, connectors, disconnect],\n );\n\n return (\n <Chains\n disabled={!selected}\n chains={chainArr}\n requiredChainIds={requiredChainIds}\n selectedWallets={selectedWallets}\n onSelectChain={handleSelectChain}\n {...props}\n />\n );\n}\n","import { Button, DialogBody, DialogFooter, Heading, Text } from \"@babylonlabs-io/core-ui\";\nimport {} from \"react\";\n\ninterface ErrorProps {\n className?: string;\n icon?: JSX.Element;\n title: string | JSX.Element;\n description: string | JSX.Element;\n cancelButton?: string | JSX.Element;\n submitButton?: string | JSX.Element;\n onCancel?: () => void;\n onSubmit?: () => void;\n}\n\nconst DEFAULT_ICON = (\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"52\" height=\"52\" viewBox=\"0 0 52 52\" fill=\"none\">\n <path\n d=\"M2.16675 46.5837H49.8334L26.0001 5.41699L2.16675 46.5837ZM28.1667 40.0837H23.8334V35.7503H28.1667V40.0837ZM28.1667 31.417H23.8334V22.7503H28.1667V31.417Z\"\n fill=\"#387085\"\n />\n </svg>\n);\n\nexport function Error({\n className,\n icon = DEFAULT_ICON,\n title,\n description,\n cancelButton = \"Cancel\",\n submitButton = (\n <>\n Continue <span className=\"hidden md:inline\">Anyway</span>\n </>\n ),\n onCancel,\n onSubmit,\n}: ErrorProps) {\n return (\n <div className={className}>\n <DialogBody className=\"py-16 text-center\">\n <div className=\"mb-6 inline-flex size-20 items-center justify-center bg-primary-contrast text-primary-light\">\n {icon}\n </div>\n\n <Heading variant=\"h4\" className=\"mb-4 text-accent-primary\">\n {title}\n </Heading>\n\n <Text as=\"div\" className=\"text-accent-secondary\">\n {description}\n </Text>\n </DialogBody>\n\n <DialogFooter className=\"flex gap-4\">\n {cancelButton && (\n <Button variant=\"outlined\" fluid onClick={onCancel}>\n {cancelButton}\n </Button>\n )}\n\n {submitButton && (\n <Button fluid onClick={onSubmit} data-testid=\"error-continue-button\">\n {submitButton}\n </Button>\n )}\n </DialogFooter>\n </div>\n );\n}\n","import { useWidgetState } from \"@/hooks/useWidgetState\";\n\nimport { Error } from \"./index\";\n\ninterface ErrorContainer {\n className?: string;\n}\n\nexport function ErrorContainer({ className }: ErrorContainer) {\n const { screen } = useWidgetState();\n const { icon, title, description, cancelButton, submitButton, onCancel, onSubmit } = screen.params ?? {};\n\n return (\n <Error\n className={className}\n icon={icon}\n title={title}\n description={description}\n cancelButton={cancelButton}\n submitButton={submitButton}\n onCancel={onCancel}\n onSubmit={onSubmit}\n />\n );\n}\n","import { Heading, Loader, Text } from \"@babylonlabs-io/core-ui\";\nimport { twMerge } from \"tailwind-merge\";\n\ninterface LoaderProps {\n className?: string;\n title?: string;\n description?: string;\n}\n\nexport function LoaderScreen({ className, title, description }: LoaderProps) {\n return (\n <div className={twMerge(\"flex flex-col items-center justify-center gap-6\", className)}>\n <div className=\"flex items-center justify-center bg-primary-contrast p-6\">\n <Loader className=\"text-primary-light\" />\n </div>\n {(title || description) && (\n <div className=\"flex flex-col items-center gap-2 text-center\">\n {title && (\n <Heading variant=\"h4\" className=\"capitalize text-accent-primary\">\n {title}\n </Heading>\n )}\n {description && (\n <Text as=\"div\" className=\"text-accent-secondary\">\n {description}\n </Text>\n )}\n </div>\n )}\n </div>\n );\n}\n","import { Chip, Text, WalletIcon } from \"@babylonlabs-io/core-ui\";\nimport { twMerge } from \"tailwind-merge\";\n\n// Green = software wallet detected/installed; yellow = hardware wallet that is\n// available but still needs connecting; secondary/gray = not installed.\nconst INSTALLED_ACCENT = \"text-[#15B768] dark:text-[#00E676]\";\nconst INSTALLED_DOT = \"bg-[#15B768] dark:bg-[#00E676]\";\nconst HARDWARE_ACCENT = \"text-[#FFB300]\";\nconst HARDWARE_DOT = \"bg-[#FFB300]\";\n\ninterface WalletButtonProps {\n className?: string;\n logo: string;\n // See `IWallet.iconBackground`.\n logoBackground?: string;\n disabled?: boolean;\n name: string;\n fallbackLink?: string;\n installed?: boolean;\n hardware?: boolean;\n label?: string;\n onClick?: () => void;\n}\n\nexport function WalletButton({\n className,\n disabled = false,\n name,\n logo,\n logoBackground,\n fallbackLink,\n installed = true,\n hardware = false,\n label,\n onClick,\n}: WalletButtonProps) {\n // Hardware wallets are always reachable through the connect flow (they have no\n // browser-extension detection step), so they show a yellow \"available\" badge\n // instead of the detection-based Installed/Uninstalled one, and are clickable\n // even when no provider is detected.\n const reachable = installed || hardware;\n const btnProps = reachable\n ? { as: \"button\", disabled, onClick }\n : { as: \"a\", href: fallbackLink, target: \"_blank\", rel: \"noopener noreferrer\" };\n\n const getTestId = () => {\n const normalizedName = name.toLowerCase();\n if (normalizedName.includes(\"okx\")) return \"wallet-option-okx\";\n if (normalizedName.includes(\"keplr\")) return \"wallet-option-keplr\";\n if (normalizedName.includes(\"leap\")) return \"wallet-option-leap\";\n return `wallet-option-${normalizedName.replace(/\\s+/g, \"-\")}`;\n };\n\n return (\n <Text\n variant=\"body2\"\n className={twMerge(\n \"flex h-14 w-full items-center gap-2.5 rounded-lg p-2 text-accent-primary\",\n installed ? \"bg-neutral-200\" : \"bg-neutral-100\",\n disabled ? \"cursor-default\" : \"cursor-pointer\",\n className,\n )}\n {...btnProps}\n data-testid={getTestId()}\n >\n <WalletIcon className=\"shrink-0\" alt={name} url={logo} background={logoBackground} />\n <span className={twMerge(\"min-w-0 flex-1 truncate text-left\", !installed && \"text-accent-secondary\")}>{name}</span>\n\n <Chip\n className={twMerge(\n \"flex shrink-0 items-center gap-1.5 rounded-full\",\n installed ? \"bg-neutral-100\" : \"bg-neutral-200\",\n )}\n >\n {(hardware || installed) && (\n <span className={twMerge(\"size-2 rounded-full\", hardware ? HARDWARE_DOT : INSTALLED_DOT)} />\n )}\n <span className={hardware ? HARDWARE_ACCENT : installed ? INSTALLED_ACCENT : \"text-accent-secondary\"}>\n {hardware ? label : installed ? \"Installed\" : \"Uninstalled\"}\n </span>\n </Chip>\n </Text>\n );\n}\n","import { Heading, Text } from \"@babylonlabs-io/core-ui\";\nimport { memo, useCallback, useMemo } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\n\nimport { WalletButton } from \"@/components/WalletButton\";\nimport { type BTCConfig, type IChain, type IWallet, Network } from \"@/core/types\";\n\nconst TAPROOT_ADDRESS_PREFIX: Record<Network, string> = {\n [Network.MAINNET]: \"bc1p\",\n [Network.TESTNET]: \"tb1p\",\n [Network.SIGNET]: \"tb1p\",\n};\n\n// Where depositors without testnet coins can request signet BTC. Only surfaced\n// on non-mainnet networks, where the \"testnet BTC\" prompt is meaningful.\nconst BTC_TESTNET_FAUCET_URL = \"https://tbv-faucet.testnet.babylonlabs.io/\";\n\nexport interface WalletsProps {\n chain: IChain;\n className?: string;\n append?: JSX.Element;\n onSelectWallet?: (chain: IChain, wallet: IWallet) => void;\n}\n\n// Connect-list ordering: installed software wallets (green) first, then\n// hardware wallets (yellow — available but need connecting), then uninstalled\n// download-only options (gray) at the bottom. A lower rank sorts higher, so\n// when no software wallet is installed the hardware options surface to the top.\nconst walletDisplayRank = (wallet: IWallet): number => {\n if (wallet.installed && !wallet.hardware) return 0;\n if (wallet.hardware) return 1;\n return 2;\n};\n\nexport const Wallets = memo(({ chain, className, append, onSelectWallet }: WalletsProps) => {\n const wallets = useMemo(\n () =>\n chain.wallets\n .filter((wallet) => (wallet.id === \"injectable\" ? wallet.installed : true))\n .sort((a, b) => walletDisplayRank(a) - walletDisplayRank(b)),\n [chain],\n );\n\n // Taproot is a hard requirement for the BTC vault, so surface the expected\n // address prefix for the connected network (bc1p on mainnet, tb1p otherwise).\n // The faucet prompt only makes sense off mainnet, where testnet coins apply.\n const btcHint = useMemo(() => {\n if (chain.id !== \"BTC\") return null;\n\n const network = (chain.config as BTCConfig | undefined)?.network;\n const prefix = network ? TAPROOT_ADDRESS_PREFIX[network] : undefined;\n if (!prefix) return null;\n\n return { prefix, showFaucet: network !== Network.MAINNET };\n }, [chain]);\n\n const handleWalletClick = useCallback(\n async (wallet: IWallet) => {\n onSelectWallet?.(chain, wallet);\n },\n [chain, onSelectWallet],\n );\n\n return (\n <div className={twMerge(\"flex flex-col overflow-hidden rounded-2xl border border-secondary-strokeLight\", className)}>\n <div className=\"flex flex-col gap-2 border-b border-secondary-strokeLight p-6\">\n <Heading variant=\"h5\" className=\"text-accent-primary\">\n {`Select ${chain.name} Wallet`}\n </Heading>\n {btcHint && (\n <Text variant=\"body2\" className=\"text-accent-secondary\">\n {`To continue, connect a ${chain.name} wallet with a `}\n <span className=\"text-accent-primary\">{`${btcHint.prefix} (Taproot)`}</span>\n {\" address.\"}\n {btcHint.showFaucet && (\n <>\n {\" Don't have testnet BTC yet? Get it from \"}\n <a\n href={BTC_TESTNET_FAUCET_URL}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-accent-primary underline underline-offset-2 transition-opacity hover:opacity-80\"\n >\n Faucet\n </a>\n {\".\"}\n </>\n )}\n </Text>\n )}\n </div>\n\n <div className=\"flex flex-col gap-4 p-6\">\n {wallets.map((wallet) => (\n <WalletButton\n installed={wallet.installed}\n hardware={wallet.hardware}\n label={wallet.label}\n key={wallet.id}\n name={wallet.name}\n logo={wallet.icon}\n logoBackground={wallet.iconBackground}\n fallbackLink={wallet.docs}\n onClick={() => handleWalletClick(wallet)}\n />\n ))}\n\n {append}\n </div>\n </div>\n );\n});\n","import { type JSX } from \"react\";\n\nimport type { IChain, IWallet } from \"@/core/types\";\nimport { useWidgetState } from \"@/hooks/useWidgetState\";\n\nimport { Wallets } from \"./index\";\n\ninterface WalletContainerProps {\n widgets?: Record<string, JSX.Element | undefined>;\n className?: string;\n append?: JSX.Element;\n onSelectWallet?: (chain: IChain, wallet: IWallet) => void;\n}\n\nexport function WalletsContainer({ widgets = {}, ...props }: WalletContainerProps) {\n const { chains, screen } = useWidgetState();\n const chainId = screen.params?.chain ?? \"\";\n const currentChain = chains?.[chainId];\n const widget = widgets?.[chainId];\n\n return <Wallets append={widget} chain={currentChain} {...props} />;\n}\n","import { type JSX } from \"react\";\n\nimport { ChainsContainer as Chains } from \"@/components/Chains/container\";\nimport { ErrorContainer as Error } from \"@/components/Error/container\";\nimport { LoaderScreen } from \"@/components/Loader\";\nimport { WalletsContainer as Wallets } from \"@/components/Wallets/container\";\nimport type { Screen } from \"@/context/State.context\";\nimport type { IChain, IWallet } from \"@/core/types\";\n\ninterface ScreenProps {\n current: Screen;\n widgets?: Record<string, JSX.Element | undefined>;\n onSelectWallet?: (chain: IChain, wallet: IWallet) => void;\n onConfirm?: () => void;\n}\n\nconst SCREENS = {\n CHAINS: ({ onConfirm }: ScreenProps) => <Chains onConfirm={onConfirm} />,\n WALLETS: ({ widgets, onSelectWallet }: ScreenProps) => <Wallets widgets={widgets} onSelectWallet={onSelectWallet} />,\n LOADER: ({ current }: ScreenProps) => (\n <LoaderScreen title={current?.params?.message as string} description={current?.params?.description as string} />\n ),\n ERROR: () => <Error />,\n EMPTY: () => <div />,\n} as const;\n\nexport function Screen(props: ScreenProps) {\n const CurrentScreen = SCREENS[props.current.type as keyof typeof SCREENS] ?? SCREENS.EMPTY;\n\n return <CurrentScreen {...props} />;\n}\n","import { FullScreenDialog } from \"@babylonlabs-io/core-ui\";\nimport { useCallback, useLayoutEffect, useRef, type ReactNode } from \"react\";\n\nimport { useChainProviders, type Connectors } from \"@/context/Chain.context\";\nimport { useLifeCycleHooks, type WalletLifecycleConnection } from \"@/context/LifecycleHooks.context\";\nimport {\n confirmedChains,\n createConfirmationReceipt,\n sameIdentity,\n subscribeToConfirmationIdentityChanges,\n WALLET_CONFIRMATION_RECEIPT_KEY,\n} from \"@/core/confirmationReceipt\";\nimport type { ChainId, HashMap, IBTCProvider, IETHProvider, IWallet } from \"@/core/types\";\nimport { useWalletConnectors, type BTCAddressValidation } from \"@/hooks/useWalletConnectors\";\nimport { useWalletWidgets } from \"@/hooks/useWalletWidgets\";\nimport { useWidgetState } from \"@/hooks/useWidgetState\";\n\nimport { Screen } from \"./Screen\";\n\nconst WALLET_CHANGED_ERROR_MESSAGE = \"Wallet changed while confirming\";\nconst WALLET_NETWORK_MISSING_ERROR_MESSAGE = \"Wallet did not report its network\";\nconst WALLET_NETWORK_MISMATCH_ERROR_MESSAGE = \"Wallet network does not match the configured network\";\nconst WALLET_PROVIDER_MISSING_ERROR_MESSAGE = \"Connected wallet has no provider\";\n\n/**\n * Picks the identity the terms-of-service hook is called with. Required chains\n * are walked in the host's declared order. Connector order can differ from it.\n */\nfunction findPrimaryConnection(\n connections: WalletLifecycleConnection[],\n requiredChainIds: string[],\n): WalletLifecycleConnection | undefined {\n for (const chainId of requiredChainIds) {\n const match = connections.find(({ chain }) => chain === chainId);\n if (match) return match;\n }\n\n return connections[0];\n}\n\nfunction collectConnections(connectors: Connectors): WalletLifecycleConnection[] {\n return Object.entries(connectors).flatMap<WalletLifecycleConnection>(([chain, connector]) => {\n const wallet = connector?.connectedWallet;\n return wallet?.account ? [{ chain: chain as ChainId, wallet, account: { ...wallet.account } }] : [];\n });\n}\n\nfunction copyConnections(connections: WalletLifecycleConnection[]): WalletLifecycleConnection[] {\n return connections.map(({ chain, wallet, account }) => {\n const accountCopy = { ...account };\n const walletCopy: IWallet = {\n id: wallet.id,\n name: wallet.name,\n icon: wallet.icon,\n iconBackground: wallet.iconBackground,\n docs: wallet.docs,\n installed: wallet.installed,\n provider: wallet.provider,\n account: accountCopy,\n label: wallet.label,\n hardware: wallet.hardware,\n };\n\n return { chain, wallet: walletCopy, account: accountCopy };\n });\n}\n\ninterface ConnectionIdentity {\n chain: ChainId;\n wallet: IWallet;\n provider: IWallet[\"provider\"];\n receipt: string;\n}\n\nfunction hasSameIdentity(\n expected: readonly ConnectionIdentity[],\n current: readonly ConnectionIdentity[],\n requiredChainIds: readonly string[],\n): boolean {\n return expected.every(({ chain, wallet, provider, receipt }) => {\n const match = current.find((identity) => identity.chain === chain);\n if (!match) return !requiredChainIds.includes(chain);\n\n return match.wallet === wallet && match.provider === provider && match.receipt === receipt;\n });\n}\n\nasync function createConfirmationSnapshot(\n getConnectors: () => Connectors,\n requiredChainIds: readonly string[],\n onOptionalError?: (error: Error) => void,\n): Promise<{\n receipt: string;\n connections: WalletLifecycleConnection[];\n identities: readonly ConnectionIdentity[];\n}> {\n const connectors = getConnectors();\n const candidates = collectConnections(connectors).map((connection) => ({\n connection,\n provider: connection.wallet.provider,\n receipt: createConfirmationReceipt([connection], connectors),\n }));\n\n const results = await Promise.all(\n candidates.map(async (candidate) => {\n const { chain } = candidate.connection;\n const { provider } = candidate;\n\n try {\n if (!provider) throw new Error(`${WALLET_PROVIDER_MISSING_ERROR_MESSAGE}: ${chain}`);\n\n if (provider.isIdentityCurrent?.() === false) {\n throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n }\n\n let network: string | number | undefined;\n if (chain === \"ETH\" || chain === \"BTC\") {\n // Fixed-network providers report their operational network here. They\n // have no independent wallet network that the user can switch.\n network =\n chain === \"ETH\"\n ? await (provider as IETHProvider).getChainId()\n : await (provider as IBTCProvider).getNetwork();\n if (network === undefined || network === null || !String(network)) {\n throw new Error(WALLET_NETWORK_MISSING_ERROR_MESSAGE);\n }\n\n const liveReceipt = createConfirmationReceipt([candidate.connection], connectors, { [chain]: network });\n if (liveReceipt !== candidate.receipt) {\n throw new Error(WALLET_NETWORK_MISMATCH_ERROR_MESSAGE);\n }\n }\n\n const [address, publicKeyHex] = await Promise.all([provider.getAddress(), provider.getPublicKeyHex()]);\n if (\n !address ||\n !publicKeyHex ||\n !sameIdentity(address, candidate.connection.account.address) ||\n !sameIdentity(publicKeyHex, candidate.connection.account.publicKeyHex)\n ) {\n throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n }\n\n if (provider.isIdentityCurrent?.() === false) {\n throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n }\n\n // IBBNProvider has no network getter. Its live account identity is\n // still checked above.\n return {\n ...candidate,\n connection: { ...candidate.connection, account: { address, publicKeyHex } },\n };\n } catch (error) {\n if (requiredChainIds.includes(chain)) throw error;\n onOptionalError?.(error instanceof Error ? error : new Error(\"Optional wallet verification failed\"));\n return null;\n }\n }),\n );\n\n const verifiedCandidates = results.filter(\n (candidate): candidate is (typeof candidates)[number] => candidate !== null,\n );\n const settledConnectors = getConnectors();\n const settledConnections = collectConnections(settledConnectors);\n const stableCandidates = verifiedCandidates.flatMap((candidate) => {\n const { connection, receipt } = candidate;\n const settled = settledConnections.find(({ chain }) => chain === connection.chain);\n const stable = Boolean(\n settled &&\n settled.wallet === connection.wallet &&\n settled.wallet.provider === candidate.provider &&\n createConfirmationReceipt([settled], settledConnectors) === receipt,\n );\n\n if (stable) return [candidate];\n if (requiredChainIds.includes(connection.chain)) throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n onOptionalError?.(new Error(WALLET_CHANGED_ERROR_MESSAGE));\n return [];\n });\n const connections = stableCandidates.map(({ connection }) => connection);\n const identities = stableCandidates.map(({ connection, provider, receipt }) => ({\n chain: connection.chain,\n wallet: connection.wallet,\n provider,\n receipt,\n }));\n\n // Restore stays synchronous until #2351 adds live session checks. Store this\n // configured receipt only after it equals the live network identity.\n return {\n receipt: createConfirmationReceipt(connections, settledConnectors),\n connections,\n identities: Object.freeze(identities),\n };\n}\n\ninterface WalletDialogProps {\n onError?: (e: Error) => void;\n btcValidation?: BTCAddressValidation;\n storage: HashMap;\n config: any;\n persistent: boolean;\n /** Optional content rendered top-right, mirroring the close/back button (e.g. a settings trigger). */\n actions?: ReactNode;\n /** Overrides the default `left-4` position of the close/back button. */\n closeButtonClassName?: string;\n /** Overrides the default `right-4` position of the `actions` slot. */\n actionsClassName?: string;\n}\n\nexport function WalletDialog({\n persistent,\n storage,\n config,\n onError,\n btcValidation,\n actions,\n closeButtonClassName,\n actionsClassName,\n}: WalletDialogProps) {\n const { visible, screen, confirmed, requiredChainIds, close, confirm, unconfirm, displayChains, displayError } =\n useWidgetState();\n const { acceptTermsOfService, onConfirm } = useLifeCycleHooks();\n const connectors = useChainProviders();\n const walletWidgets = useWalletWidgets(connectors, config, onError);\n const { connect } = useWalletConnectors({ persistent, accountStorage: storage, onError, btcValidation });\n\n const connectorsRef = useRef(connectors);\n const attemptGenerationRef = useRef(0);\n const activeAttemptRef = useRef<number | null>(null);\n const activeIdentitySubscriptionRef = useRef<(() => void) | null>(null);\n const mountedRef = useRef(false);\n const visibleRef = useRef(visible);\n const confirmedRef = useRef(confirmed);\n const confirmationInputsRef = useRef({ persistent, requiredChainIds: [...requiredChainIds], storage });\n\n const invalidateAttempt = useCallback(() => {\n const stopWatchingIdentity = activeIdentitySubscriptionRef.current;\n activeIdentitySubscriptionRef.current = null;\n attemptGenerationRef.current += 1;\n activeAttemptRef.current = null;\n stopWatchingIdentity?.();\n }, []);\n\n useLayoutEffect(() => {\n connectorsRef.current = connectors;\n if ((visibleRef.current && !visible) || (!confirmedRef.current && confirmed)) invalidateAttempt();\n visibleRef.current = visible;\n confirmedRef.current = confirmed;\n }, [confirmed, connectors, invalidateAttempt, visible]);\n\n useLayoutEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n invalidateAttempt();\n };\n }, [invalidateAttempt]);\n\n useLayoutEffect(() => {\n const previous = confirmationInputsRef.current;\n const requiredChainsChanged =\n previous.requiredChainIds.length !== requiredChainIds.length ||\n previous.requiredChainIds.some((chainId, index) => chainId !== requiredChainIds[index]);\n\n if (previous.persistent !== persistent || previous.storage !== storage || requiredChainsChanged) {\n invalidateAttempt();\n }\n confirmationInputsRef.current = { persistent, requiredChainIds: [...requiredChainIds], storage };\n }, [invalidateAttempt, persistent, requiredChainIds, storage]);\n\n // Closing without confirming leaves the connectors connected, so the user can\n // reopen and finish where they left off. The receipt written on confirm is\n // the single gate that lets a later reload auto-confirm — no receipt, no\n // silent restore — so leaving the connection up grants nothing on its own.\n const handleClose = useCallback(() => {\n invalidateAttempt();\n close?.();\n }, [close, invalidateAttempt]);\n\n const handleConfirm = useCallback(async () => {\n if (activeAttemptRef.current !== null || !mountedRef.current || !visibleRef.current) return;\n\n const generation = attemptGenerationRef.current + 1;\n attemptGenerationRef.current = generation;\n activeAttemptRef.current = generation;\n const isCurrentAttempt = () =>\n activeAttemptRef.current === generation &&\n attemptGenerationRef.current === generation &&\n mountedRef.current &&\n visibleRef.current;\n let stopWatchingIdentity = () => {};\n let confirmationHandoffPending = false;\n\n try {\n if (!confirmed) {\n const initialConnectors = connectorsRef.current;\n const initialReceipt = createConfirmationReceipt(collectConnections(initialConnectors), initialConnectors);\n const unsubscribeIdentity = subscribeToConfirmationIdentityChanges(\n initialReceipt,\n confirmedChains(initialReceipt),\n initialConnectors,\n () => {\n invalidateAttempt();\n storage.delete(WALLET_CONFIRMATION_RECEIPT_KEY);\n unconfirm?.();\n },\n );\n let watchingIdentity = true;\n stopWatchingIdentity = () => {\n if (!watchingIdentity) return;\n watchingIdentity = false;\n unsubscribeIdentity();\n };\n if (!isCurrentAttempt()) {\n stopWatchingIdentity();\n return;\n }\n activeIdentitySubscriptionRef.current = stopWatchingIdentity;\n\n const confirmationSnapshot = await createConfirmationSnapshot(\n () => connectorsRef.current,\n requiredChainIds,\n onError,\n );\n if (!isCurrentAttempt()) return;\n const { connections } = confirmationSnapshot;\n\n // A required chain whose connector has no active account would\n // otherwise drop silently out of `connections` and be confirmed with\n // nothing recorded for it, leaving the next reload to ask again with no\n // signal that anything went wrong.\n const uncovered = requiredChainIds.filter((chainId) => !connections.some(({ chain }) => chain === chainId));\n if (uncovered.length > 0) {\n throw new Error(\n `No connected account for required chain${uncovered.length > 1 ? \"s\" : \"\"}: ${uncovered.join(\", \")}`,\n );\n }\n\n const primary = findPrimaryConnection(connections, requiredChainIds);\n const checkIdentity = async () => {\n if (!isCurrentAttempt()) return false;\n\n const currentSnapshot = await createConfirmationSnapshot(\n () => connectorsRef.current,\n requiredChainIds,\n onError,\n );\n if (!isCurrentAttempt()) return false;\n\n if (!hasSameIdentity(confirmationSnapshot.identities, currentSnapshot.identities, requiredChainIds)) {\n throw new Error(WALLET_CHANGED_ERROR_MESSAGE);\n }\n\n return true;\n };\n\n if (primary) {\n await acceptTermsOfService?.({\n address: primary.account.address,\n public_key: primary.account.publicKeyHex,\n chain: primary.chain,\n connections: copyConnections(connections),\n });\n if (!(await checkIdentity())) return;\n }\n await onConfirm?.(copyConnections(connections));\n if (!(await checkIdentity())) return;\n\n if (persistent) {\n storage.set(WALLET_CONFIRMATION_RECEIPT_KEY, confirmationSnapshot.receipt);\n }\n\n if (!isCurrentAttempt()) return;\n confirm?.(confirmationSnapshot.receipt);\n if (!isCurrentAttempt()) return;\n confirmationHandoffPending = Boolean(confirm);\n }\n\n if (!isCurrentAttempt()) return;\n close?.();\n } catch (error) {\n if (!isCurrentAttempt()) return;\n\n const normalizedError = error instanceof Error ? error : new Error(\"Wallet confirmation failed\");\n onError?.(normalizedError);\n if (!isCurrentAttempt()) return;\n displayError?.({\n title: \"Connection Failed\",\n description: normalizedError.message,\n submitButton: \"\",\n cancelButton: \"Done\",\n onCancel: displayChains,\n });\n } finally {\n if (!confirmationHandoffPending) {\n stopWatchingIdentity();\n if (activeIdentitySubscriptionRef.current === stopWatchingIdentity) {\n activeIdentitySubscriptionRef.current = null;\n }\n if (attemptGenerationRef.current === generation && activeAttemptRef.current === generation) {\n activeAttemptRef.current = null;\n }\n }\n }\n }, [\n acceptTermsOfService,\n close,\n confirm,\n confirmed,\n displayChains,\n displayError,\n invalidateAttempt,\n onConfirm,\n onError,\n persistent,\n requiredChainIds,\n storage,\n unconfirm,\n ]);\n\n const onBack = screen.type === \"WALLETS\" ? displayChains : undefined;\n\n return (\n <FullScreenDialog\n open={visible}\n onClose={handleClose}\n onBack={onBack}\n className=\"items-center justify-center p-6\"\n actions={actions}\n closeButtonClassName={closeButtonClassName}\n actionsClassName={actionsClassName}\n >\n <div className=\"mx-auto w-full max-w-[612px]\">\n <Screen current={screen} widgets={walletWidgets} onConfirm={handleConfirm} onSelectWallet={connect} />\n </div>\n </FullScreenDialog>\n );\n}\n","import { useEffect, useRef } from \"react\";\n\ninterface UseVisibilityCheckOptions {\n /** Whether the visibility check is enabled */\n enabled: boolean;\n /** Delay in ms before running the check (default: 500) */\n delay?: number;\n}\n\n/**\n * Runs a callback when the document becomes visible.\n * Useful for checking wallet connections when user returns to the tab.\n */\nexport function useVisibilityCheck(\n onVisible: () => void | Promise<void>,\n options: UseVisibilityCheckOptions,\n) {\n const { enabled, delay = 500 } = options;\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n if (!enabled) return;\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n\n const handleVisibilityChange = () => {\n if (document.visibilityState === \"visible\") {\n // Clear any existing timeout before scheduling a new one\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n timeoutRef.current = setTimeout(() => {\n // Wrap async callback to catch unhandled rejections\n Promise.resolve(onVisible()).catch((error) => {\n console.error(\"Error in visibility check callback:\", error instanceof Error ? error.message : \"Unknown error\");\n });\n }, delay);\n }\n };\n\n document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n\n return () => {\n document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n // Clear pending timeout on cleanup\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n };\n }, [enabled, onVisible, delay]);\n}\n","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type PropsWithChildren,\n} from \"react\";\n\nimport type { IETHProvider } from \"@/core/types\";\nimport { useChainConnector } from \"@/hooks/useChainConnector\";\nimport { useVisibilityCheck } from \"@/hooks/useVisibilityCheck\";\nimport { useWalletConnect } from \"@/hooks/useWalletConnect\";\n\nexport interface ETHWalletLifecycleCallbacks {\n onConnect?: (address: string) => void | Promise<void>;\n onDisconnect?: () => void | Promise<void>;\n onAddressChange?: (newAddress: string) => void | Promise<void>;\n onError?: (error: Error, context?: { address?: string }) => void;\n}\n\ninterface ETHWalletContextType {\n loading: boolean;\n connected: boolean;\n address: string | undefined;\n disconnect: () => void;\n open: () => void;\n}\n\nconst ETHWalletContext = createContext<ETHWalletContextType>({\n loading: true,\n connected: false,\n address: undefined,\n disconnect: () => {},\n open: () => {},\n});\n\nexport interface ETHWalletProviderProps extends PropsWithChildren {\n callbacks?: ETHWalletLifecycleCallbacks;\n}\n\nexport const ETHWalletProvider = ({ children, callbacks }: ETHWalletProviderProps) => {\n const [loading, setLoading] = useState(true);\n const [address, setAddress] = useState<string>();\n const [provider, setProvider] = useState<IETHProvider | null>(null);\n\n const { open, disconnect: disconnectWallet } = useWalletConnect();\n const ethConnector = useChainConnector(\"ETH\");\n\n const disconnectLocally = useCallback(async () => {\n try {\n await ethConnector?.disconnect(\"local\");\n } catch (error) {\n console.error(\"Failed to disconnect ETH connector:\", error instanceof Error ? error.message : \"Unknown error\");\n }\n }, [ethConnector]);\n\n const connectETH = useCallback(\n async (walletAddress: string) => {\n try {\n setAddress(walletAddress);\n setLoading(false);\n\n await callbacks?.onConnect?.(walletAddress);\n } catch (error: unknown) {\n setLoading(false);\n callbacks?.onError?.(error instanceof Error ? error : new Error(\"ETH connection failed\"), {\n address: walletAddress,\n });\n }\n },\n [callbacks],\n );\n\n // Check for existing connection on mount (handles auto-reconnection)\n useEffect(() => {\n setLoading(false);\n if (!ethConnector) return;\n\n const checkExistingConnection = async () => {\n try {\n // First check if connector already has a connected wallet\n if (ethConnector.connectedWallet?.provider && !address) {\n const walletProvider = ethConnector.connectedWallet.provider;\n const addr = await walletProvider.getAddress();\n if (addr) {\n setProvider(walletProvider);\n connectETH(addr);\n }\n return;\n }\n\n // If not, try to auto-reconnect using the first available wallet\n // The AppKitProvider will detect existing wagmi connection and return immediately\n if (!address && ethConnector.wallets.length > 0) {\n const wallet = ethConnector.wallets[0]; // AppKit wallet\n if (wallet.provider) {\n try {\n // This will check for existing connection and return immediately if found\n const addr = await wallet.provider.getAddress();\n if (addr) {\n // Found existing connection, trigger manual connect to sync state\n await ethConnector.connect(wallet);\n }\n } catch (error) {\n // No existing connection, which is fine\n }\n }\n }\n } catch (error) {\n // No existing connection, which is fine\n }\n };\n\n checkExistingConnection();\n\n const unsubscribe = ethConnector.on(\"connect\", async (wallet) => {\n if (wallet.provider) {\n try {\n const addr = await wallet.provider.getAddress();\n if (addr) {\n setProvider(wallet.provider);\n connectETH(addr);\n }\n } catch (error) {\n console.error(\"Error getting ETH address:\", error instanceof Error ? error.message : \"Unknown error\");\n }\n }\n });\n\n // Restore connector state when wagmi restores the account after mount.\n // The existing wagmi connection keeps this call from opening the modal.\n const bootstrapWallet = ethConnector.wallets[0];\n const bootstrapProvider = bootstrapWallet?.provider;\n // Block duplicate events until React receives the restored address.\n let lateReconnectInFlight = false;\n const onLateReconnect = (accounts?: string[]) => {\n if (!accounts?.[0] || address || lateReconnectInFlight) return;\n lateReconnectInFlight = true;\n void ethConnector\n .connect(bootstrapWallet)\n .then((wallet) => {\n // A failed connection resolves null. Let the next event try again.\n if (!wallet) lateReconnectInFlight = false;\n })\n .catch((error) => {\n // Also allow a retry after an unexpected error.\n lateReconnectInFlight = false;\n console.error(\"ETH late reconnect failed:\", error instanceof Error ? error.message : \"Unknown error\");\n });\n };\n if (bootstrapProvider && typeof bootstrapProvider.on === \"function\") {\n bootstrapProvider.on(\"accountsChanged\", onLateReconnect);\n }\n\n return () => {\n unsubscribe();\n if (bootstrapProvider && typeof bootstrapProvider.off === \"function\") {\n bootstrapProvider.off(\"accountsChanged\", onLateReconnect);\n }\n };\n }, [ethConnector, connectETH, address]);\n\n useEffect(() => {\n if (!ethConnector) return;\n\n return ethConnector.on(\"disconnect\", async () => {\n setAddress(undefined);\n setProvider(null);\n try {\n await callbacks?.onDisconnect?.();\n } catch (error) {\n console.error(\"Error in onDisconnect callback:\", error instanceof Error ? error.message : \"Unknown error\");\n }\n });\n }, [ethConnector, callbacks]);\n\n // Track previous address to detect changes\n const prevAddressRef = useRef<string | undefined>(undefined);\n // Guard against duplicate event processing from provider and window.ethereum\n const isProcessingChangeRef = useRef(false);\n\n // Keep the ref in sync with React state\n useEffect(() => {\n prevAddressRef.current = address;\n }, [address]);\n\n // Listen for ETH account changes on the provider\n // Using provider state ensures React properly tracks when provider becomes available\n useEffect(() => {\n if (!provider) return;\n\n const onAccountsChanged = async (accounts: string[]) => {\n // Prevent duplicate processing if both provider and window.ethereum fire events\n if (isProcessingChangeRef.current) return;\n\n const newAddress = accounts[0];\n const previousAddress = prevAddressRef.current;\n\n if (newAddress && newAddress.toLowerCase() !== previousAddress?.toLowerCase()) {\n // Account changed - set guard before async operations\n isProcessingChangeRef.current = true;\n prevAddressRef.current = newAddress;\n setAddress(newAddress);\n try {\n await callbacks?.onAddressChange?.(newAddress);\n } catch (error: unknown) {\n callbacks?.onError?.(error instanceof Error ? error : new Error(\"ETH address change failed\"), {\n address: newAddress,\n });\n } finally {\n isProcessingChangeRef.current = false;\n }\n } else if (!newAddress && previousAddress) {\n disconnectLocally();\n }\n };\n\n if (typeof provider.on === \"function\") {\n provider.on(\"accountsChanged\", onAccountsChanged);\n }\n\n return () => {\n if (typeof provider.off === \"function\") {\n provider.off(\"accountsChanged\", onAccountsChanged);\n }\n };\n }, [provider, callbacks, disconnectLocally]);\n\n // Use only the active provider. window.ethereum can report unrelated accounts.\n\n // Check for wallet changes when the user returns to the tab.\n const checkETHConnection = useCallback(async () => {\n if (!provider) return;\n\n try {\n const currentAddress = await provider.getAddress();\n\n if (!currentAddress) {\n disconnectLocally();\n } else if (currentAddress.toLowerCase() !== address?.toLowerCase()) {\n // Account changed while tab was in background\n prevAddressRef.current = currentAddress;\n setAddress(currentAddress);\n await callbacks?.onAddressChange?.(currentAddress);\n }\n } catch (error) {\n console.error(\"ETH wallet connection check failed:\", error instanceof Error ? error.message : \"Unknown error\");\n disconnectLocally();\n }\n }, [provider, address, callbacks, disconnectLocally]);\n\n useVisibilityCheck(checkETHConnection, {\n enabled: Boolean(provider && address),\n });\n\n const connected = useMemo(() => Boolean(address), [address]);\n\n return (\n <ETHWalletContext.Provider\n value={{\n loading,\n connected,\n address,\n disconnect: () => disconnectWallet(\"ETH\"),\n open,\n }}\n >\n {children}\n </ETHWalletContext.Provider>\n );\n};\n\nexport const useETHWallet = () => useContext(ETHWalletContext);\n"],"names":["getDefaultExportFromCjs","x","browser","process","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","runClearTimeout","marker","queue","draining","currentQueue","queueIndex","cleanUpNextTick","drainQueue","timeout","len","args","i","Item","array","noop","name","dir","browserExports","process$1","ACCOUNT_CHANGE_EVENTS","isAccountChangeEvent","eventName","NETWORK_CHANGE_EVENT","DISCONNECT_EVENT","trackProviderIdentityChanges","provider","callback","event","_a","WALLET_MODAL_OPEN_EVENT","COSMOS_KEYSTORE_CHANGE_EVENTS","removeProviderListener","ONE_HOUR","Wallet","id","origin","icon","iconBackground","docs","networks","label","hardware","__publicField","onProgress","address","publicKeyHex","createNanoEvents","callbacks","length","cb","ERROR_CODES","WalletError","code","message","wallet","version","chainId","options","isUserRejectionMessage","lower","isSharedSessionRefusal","error","WalletConnector","wallets","config","selectedWallet","w","reportProgress","description","e","scope","generation","handler","Network","defaultWalletGetter","key","context","createWallet","metadata","walletGetter","nameGetter","iconGetter","createProvider","getWallet","createExternalWallet","createWalletConnector","persistent","accountStorage","disabledWallets","connectedWalletId","walletMetadata","injectableWallet","filteredWallets","connector","selectRedetectReconnectTargets","connectors","storage","allowReconnect","eligibleChainIds","targets","storedWalletId","UNISAT_READY_EVENT","FALLBACK_MS","useWalletRedetection","setConnectors","connectorsRef","useRef","connectorsBuilt","useEffect","inFlight","cancelled","reconnecting","pendingRestore","redetect","runRedetection","stale","c","swapIn","rebuilt","cc","appeared","before","wasInstalled","current","prev","next","inState","reconnectTargets","walletId","redetectColdStart","redetectInteractive","timer","hasWindow","usePersistState","initialState","getDefaultState","defaultValue","persistValue","state","setState","useState","Context","createContext","InscriptionProvider","children","lockInscriptions","toggleLockInscriptions","inscriptionContext","useMemo","useInscriptionProvider","useContext","WALLET_CONFIRMATION_RECEIPT_KEY","RECEIPT_VERSION","IDENTITY_CHANGE_EVENTS","connectorFor","chain","networkIdentity","value","sameIdentity","left","right","isReceiptEntry","entry","parseConfirmationReceipt","serialized","receipt","createConfirmationReceipt","connections","entries","connection","isValidConfirmationReceipt","requiredChainIds","account","candidate","isConfirmationReceiptCovered","isLiveConfirmationReceiptValid","network","_b","subscribeToConfirmationIdentityChanges","onChange","subscriptions","_c","accounts","approved","confirmedChains","defaultState","StateContext","filterWalletsByValidChains","selectedWallets","validChainIds","acc","StateProvider","chains","requirementsExpanded","renderedState","requiredChainIdsRef","useInsertionEffect","newChains","actions","params","required","confirmationReceipt","keepReceipt","ChainProvider","onError","requiredChains","init","useCallback","connectorPromises","chainMetadata","active","bump","unsubscribe","fn","supportedChains","jsx","useChainProviders","LifeCycleHooksProvider","useLifeCycleHooks","CONNECTED_ACCOUNTS_KEY","scopeKey","networkMap","readAccountsMap","raw","parsed","writeAccountsMap","map","createAccountStorage","ttl","getTimestamps","timestamps","isExpired","scoped","ts","now","deleted","MONOCHROME_MARK_BACKGROUND","ONEKEY_BRAND_GREEN","okxLogo","APPKIT_OPEN_EVENT","APPKIT_ETH_CONNECTOR_ID","APPKIT_BTC_CONNECTOR_ID","BIGINT_FINGERPRINT_TYPE","FUNCTION_FINGERPRINT_TYPE","CONFIG_FINGERPRINT_SERIALIZATION_ERROR","INITIAL_CONFIG_FUNCTION_ID","configFunctionIds","nextConfigFunctionId","getConfigFunctionId","existingId","createConfigFingerprint","fingerprint","_key","nestedValue","createAppKitCapabilities","projectId","ethChain","btcNetwork","appKitState","manualAppKitModal","manualAppKitCapabilities","failInitialization","getAppKitState","getAppKitModal","registerManualAppKitConfig","capability","modal","validateAppKitInitialization","setAppKitState","assertAppKitCapabilities","existing","requested","ETHEREUM_CAPABILITY","SHARED_WAGMI_REPLACEMENT_WARNING","sharedWagmiConfig","setSharedWagmiConfig","getSharedWagmiConfig","initializedState","hasSharedWagmiConfig","ethDisconnectWouldDropBitcoin","MODAL_CLOSE_CANCEL_GRACE_MS","WALLET_NOT_CONNECTED_ERROR_MESSAGE","ETH_FALLBACK_PROVIDER_NAME","ETH_FALLBACK_PROVIDER_ICON","AppKitProvider","initialAccount","getAccount","unwatchAccount","watchAccount","previousAddress","unwatchChain","watchChainId","previousChainId","data","handlers","currentAccount","resolve","reject","modalHasOpened","pendingCancellation","cleanup","unwatch","unsubscribeModal","latestAccount","wcConnector","walletConnect","result","connect","wagmiDisconnect","wagmiSignMessage","typedData","wagmiSignTypedData","tx","wagmiSendTransaction","parseEther","wagmiEstimateGas","wagmiSwitchChain","wagmiGetBalance","getTransactionCount","walletInfo","WALLET_PROVIDER_NAME","_wallet","appkit","createETHWagmiAdapter","ethRpcUrl","WagmiAdapter","createStorage","cookieStorage","baseAccount","http","initializeAppKitModal","capabilities","existingState","reownAppKitModal","wagmiAdapter","createAppKit","useAppKitOpenListener","handleOpenRequest","useChainConnector","FIRST_PARTY_ICONS","resolveFirstPartyIcon","walletName","match","useWidgetState","resolveEthDisplayWallet","firstParty","TERMINAL_CONNECT_ERROR_CODES","useWalletConnectors","btcValidation","confirmed","visible","selectWallet","removeWallet","displayLoader","displayChains","displayError","confirm","unconfirm","verifyBTCAddress","validationGenerationRef","previousRequiredChainIdsRef","confirmationCandidate","confirmationCandidateRef","dirtyOptionalChainsRef","requiredConnectorsReady","droppingRef","dropRejectedWallet","unsubscribeArr","connectorArr","connectedWallet","goToNextScreen","_d","useLayoutEffect","validateConfirmation","covered","previousCandidate","newlyRequiredChainIds","stopWatchingIdentity","useWalletWidgets","createChainWidget","externalConnectors","Fragment","Component","useWalletConnect","chainMap","openModal","displayWallets","reset","open","disconnect","selected","ChainButton","className","alt","logo","title","onClick","avatar","Avatar","getTestId","jsxs","Text","twMerge","ADDRESS_TRUNCATE_THRESHOLD","ADDRESS_EDGE_CHARS","truncateAddress","ConnectedWallet","memo","logoBackground","isCopied","copyToClipboard","useCopy","copied","handleCopy","WalletIcon","CheckIcon","CopyIcon","DISABLED_CONNECT_BG","SELECT_WALLET_TITLE_PREFIX","SELECT_WALLET_TITLE_SUFFIX","OPTIONAL_CHAIN_TITLE_SUFFIX","Chains","disabled","onConfirm","onSelectChain","Heading","optional","Button","openAppKitModal","ChainsContainer","props","chainArr","handleSelectChain","appkitId","connected","DEFAULT_ICON","Error","cancelButton","submitButton","onCancel","onSubmit","DialogBody","DialogFooter","ErrorContainer","screen","LoaderScreen","Loader","INSTALLED_ACCENT","INSTALLED_DOT","HARDWARE_ACCENT","HARDWARE_DOT","WalletButton","fallbackLink","installed","btnProps","normalizedName","Chip","TAPROOT_ADDRESS_PREFIX","BTC_TESTNET_FAUCET_URL","walletDisplayRank","Wallets","append","onSelectWallet","a","b","btcHint","prefix","handleWalletClick","WalletsContainer","widgets","currentChain","widget","SCREENS","Screen","CurrentScreen","WALLET_CHANGED_ERROR_MESSAGE","WALLET_NETWORK_MISSING_ERROR_MESSAGE","WALLET_NETWORK_MISMATCH_ERROR_MESSAGE","WALLET_PROVIDER_MISSING_ERROR_MESSAGE","findPrimaryConnection","collectConnections","copyConnections","accountCopy","walletCopy","hasSameIdentity","expected","identity","createConfirmationSnapshot","getConnectors","onOptionalError","candidates","verifiedCandidates","settledConnectors","settledConnections","stableCandidates","settled","identities","WalletDialog","closeButtonClassName","actionsClassName","close","acceptTermsOfService","walletWidgets","attemptGenerationRef","activeAttemptRef","activeIdentitySubscriptionRef","mountedRef","visibleRef","confirmedRef","confirmationInputsRef","invalidateAttempt","previous","requiredChainsChanged","index","handleClose","handleConfirm","isCurrentAttempt","confirmationHandoffPending","initialConnectors","initialReceipt","unsubscribeIdentity","watchingIdentity","confirmationSnapshot","uncovered","primary","checkIdentity","currentSnapshot","normalizedError","onBack","FullScreenDialog","useVisibilityCheck","onVisible","enabled","delay","timeoutRef","handleVisibilityChange","ETHWalletContext","ETHWalletProvider","loading","setLoading","setAddress","setProvider","disconnectWallet","ethConnector","disconnectLocally","connectETH","walletAddress","walletProvider","addr","bootstrapWallet","bootstrapProvider","lateReconnectInFlight","onLateReconnect","prevAddressRef","isProcessingChangeRef","onAccountsChanged","newAddress","checkETHConnection","currentAddress","useETHWallet"],"mappings":";;;;;;;;;;;;;AAAA,SAASA,GAAyBC,GAAG;AACpC,SAAOA,KAAKA,EAAE,cAAc,OAAO,UAAU,eAAe,KAAKA,GAAG,SAAS,IAAIA,EAAE,UAAaA;AACjG;AAEA,IAAIC,KAAU,EAAC,SAAS,GAAE,GAGtBC,IAAUD,GAAQ,UAAU,CAAA,GAO5BE,GACAC;AAEJ,SAASC,KAAmB;AACxB,QAAM,IAAI,MAAM,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