@usebutr/core 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["VALID_CHAIN_PLATFORMS","isValidAccount","isValidPoolEntry","toCookieMap"],"sources":["../src/types/chains-by-platform.ts","../src/types/errors.ts","../src/types/wallet.ts","../src/wallet-source.ts","../src/logger.ts","../src/storage/browser-storage-driver.ts","../src/storage/wallet-storage.ts","../src/store/connector-lifecycle.ts","../src/store/hydration.ts","../src/store/reducer.ts","../src/store/shadow-adapter.ts","../src/store/wallet-store-helpers.ts","../src/store/wallet-store.ts","../src/storage/cookie-storage-driver.ts","../src/storage/snapshot.ts","../src/wallet-equal.ts","../src/sanitize-icon.ts","../src/encoding/bytes.ts"],"sourcesContent":["import type { ChainBase } from \"./chain\";\nimport type { ChainPlatform } from \"./wallet\";\n\n/**\n * Map of every chain platform to the list of chains the consumer wants\n * to expose to its UI (chain switcher, picker, etc).\n *\n * The platform key set is fixed by `ChainPlatform`. The value is the\n * chain list — empty when the consumer doesn't want to support that\n * platform's chains in this view. This is the only type that callers\n * write down; the values come from per-platform packages\n * (`EVM_CHAINS_LIST`, `SVM_CHAINS_LIST`, etc).\n */\ntype ChainsByPlatform = Readonly<Record<ChainPlatform, ReadonlyArray<ChainBase>>>;\n\n/**\n * Build a fully-populated `ChainsByPlatform` from a partial. Platforms\n * the consumer doesn't specify default to an empty list.\n *\n * Use this in apps that target one or two chain platforms — importing\n * only those packages keeps unused chain registries out of the bundle.\n * Apps that want every chain reach for `CHAINS_BY_PLATFORM` from\n * `@usebutr/wallets` instead.\n *\n * @example\n * // EVM-only app — Solana/Sui/Bitcoin tables never enter the bundle\n * import { EVM_CHAINS_LIST } from \"@usebutr/evm\";\n * import { buildChainsByPlatform } from \"@usebutr/core\";\n *\n * const chains = buildChainsByPlatform({ evm: EVM_CHAINS_LIST });\n *\n * @example\n * // Multi-chain app — pull from each package the app actually uses\n * import { EVM_CHAINS_LIST } from \"@usebutr/evm\";\n * import { SVM_CHAINS_LIST } from \"@usebutr/svm\";\n *\n * const chains = buildChainsByPlatform({\n * evm: EVM_CHAINS_LIST,\n * svm: SVM_CHAINS_LIST,\n * });\n */\nconst buildChainsByPlatform = (partial: Partial<ChainsByPlatform>): ChainsByPlatform => ({\n bitcoin: partial.bitcoin ?? [],\n evm: partial.evm ?? [],\n polkadot: partial.polkadot ?? [],\n sui: partial.sui ?? [],\n svm: partial.svm ?? [],\n});\n\nexport type { ChainsByPlatform };\nexport { buildChainsByPlatform };\n","/**\n * Tagged union of normalised connection errors.\n *\n * butr maps thrown values from connectors (which vary across wallet SDKs:\n * MetaMask uses EIP-1193 codes, Phantom throws stringly-typed errors,\n * embedded SDKs throw their own classes) into a small set of UX-meaningful\n * variants. Consumers branch on `kind` instead of regexing message strings.\n *\n * `message` is always present and human-readable. `cause` preserves the\n * original thrown value so callers can inspect raw connector errors when\n * the variant is `Unknown`.\n */\ntype ConnectionError =\n | { kind: \"UserRejected\"; message: string }\n | { kind: \"RequestPending\"; message: string }\n | { kind: \"WalletLocked\"; message: string }\n | { actualChain?: string; expectedChain?: string; kind: \"ChainMismatch\"; message: string }\n | { kind: \"NotConnected\"; message: string }\n | { kind: \"Timeout\"; message: string }\n | { cause?: unknown; kind: \"Unknown\"; message: string };\n\ntype ConnectionErrorKind = ConnectionError[\"kind\"];\n\n/**\n * Normalise a thrown value into a `ConnectionError`.\n *\n * Recognises:\n * - butr's own `Error(\"Connection timeout\")` (from the 90s connect timeout)\n * - butr's own `Error(\"Failed to get account\")` (from the connect flow)\n * - EIP-1193 numeric `code` properties (`4001` → UserRejected,\n * `-32002` → RequestPending, `4100`/`4900`/`4901` → NotConnected —\n * unauthorized / disconnected from all-or-one chains)\n * - common message substrings: \"user rejected\" / \"user denied\",\n * \"locked\", \"chain\", etc.\n * - anything else → `Unknown` with `cause` set to the original value.\n */\nconst mapConnectionError = (raw: unknown): ConnectionError => {\n if (raw instanceof Error) {\n const message = raw.message;\n const lower = message.toLowerCase();\n\n if (message === \"Connection timeout\") {\n return { kind: \"Timeout\", message };\n }\n if (message === \"Failed to get account\" || lower.includes(\"not connected\")) {\n return { kind: \"NotConnected\", message };\n }\n\n const code = (raw as { code?: unknown }).code;\n if (code === 4001) {\n return { kind: \"UserRejected\", message };\n }\n if (code === -32_002) {\n return { kind: \"RequestPending\", message };\n }\n // EIP-1193: 4100 unauthorized, 4900 disconnected (all chains),\n // 4901 disconnected (requested chain). All mean \"no usable session\"\n // from butr's perspective → NotConnected.\n if (code === 4100 || code === 4900 || code === 4901) {\n return { kind: \"NotConnected\", message };\n }\n\n if (lower.includes(\"user rejected\") || lower.includes(\"user denied\")) {\n return { kind: \"UserRejected\", message };\n }\n if (lower.includes(\"locked\")) {\n return { kind: \"WalletLocked\", message };\n }\n if (lower.includes(\"chain\") && (lower.includes(\"mismatch\") || lower.includes(\"unsupported\"))) {\n return { kind: \"ChainMismatch\", message };\n }\n\n return { cause: raw, kind: \"Unknown\", message };\n }\n\n if (typeof raw === \"string\") {\n return { kind: \"Unknown\", message: raw };\n }\n\n return { cause: raw, kind: \"Unknown\", message: \"Connection failed\" };\n};\n\nexport type { ConnectionError, ConnectionErrorKind };\nexport { mapConnectionError };\n","import type { WalletPersistence } from \"../storage/persistence\";\nimport type { WalletSnapshot } from \"../storage/snapshot\";\n\nimport type { ChainBase } from \"./chain\";\nimport type { ConnectionError } from \"./errors\";\n\n/**\n * Canonical list of supported chain platforms. The single runtime source\n * of truth: `ChainPlatform` is derived from it, and storage validators\n * build their allowlists from it, so the type and the runtime checks can\n * never drift (a missing platform here was why Polkadot connections failed\n * to persist).\n */\nconst CHAIN_PLATFORMS = [\"evm\", \"svm\", \"sui\", \"bitcoin\", \"polkadot\"] as const;\n\ntype ChainPlatform = (typeof CHAIN_PLATFORMS)[number];\n\ntype Account = {\n chain: ChainBase;\n id: string;\n walletAddress: string;\n};\n\ntype Balance = {\n /** Token decimals (e.g. 9 for SOL, 18 for ETH) */\n decimals: number;\n /** Human-readable string, trimmed of trailing zeros */\n formatted: string;\n /** Token symbol (e.g. \"SOL\", \"ETH\") */\n symbol: string;\n /** Raw integer amount */\n value: bigint;\n};\n\n/**\n * Whether a wallet is currently usable from the user's environment.\n *\n * - `installed` — the wallet is available and `connect()` can be called.\n * - `loadable` — the wallet's SDK can be loaded on demand (e.g. WalletConnect\n * modal that pops a QR code without requiring a browser extension).\n * - `not-installed` — the wallet isn't reachable. Consumers typically render\n * a \"download\" affordance pointing at `meta.url`.\n */\ntype WalletAvailability = \"installed\" | \"loadable\" | \"not-installed\";\n\n/**\n * Events a connector can emit while connected. butr's runtime subscribes\n * via `Connector.subscribe?` after a successful `connect()` and dispatches\n * the equivalent reducer event:\n *\n * - `accountChanged` carries both the new active `account` AND the full\n * `accounts` array the wallet currently exposes. The runtime mirrors\n * that list verbatim into the pool entry. This handles two cases\n * uniformly:\n * - Multi-account wallets (MetaMask, Rabby, Brave): the user adds or\n * removes accounts from the dapp's permission set; the array grows\n * or shrinks to match.\n * - Single-account-exposure wallets (Phantom EVM/SVM, MetaMask Snap):\n * only the active account is ever in `accounts`; switching swaps it\n * in place rather than appending.\n * Also covers chain switches — the new chain lives inside `account.chain`.\n * - `disconnected` → `DISCONNECTED` (wallet has gone away externally:\n * user locked it, removed the extension, etc.).\n */\ntype ConnectorEvent =\n | { account: Account; accounts: Array<Account>; type: \"accountChanged\" }\n | { type: \"disconnected\" };\n\n/**\n * Capability flags describing what an adapter can actually do at\n * runtime. Populated by each adapter (the auto-built ones derive\n * these from the underlying protocol's feature advertisements;\n * hand-rolled adapters declare them explicitly). Consumers branch on\n * these to gate UI affordances:\n *\n * ```tsx\n * {wallet.connector.capabilities.requestAccounts ? (\n * <button onClick={() => requestAccounts(wallet.connector.id)}>\n * Request more accounts\n * </button>\n * ) : null}\n * ```\n *\n * Each flag means \"can this work right now,\" not \"is the method\n * defined\": `signMessage: false` means calling `signMessage()` would\n * reject; `switchChain: false` means switching is a no-op regardless\n * of which chain is passed.\n */\ntype WalletCapabilities = {\n /** `getBalance` returns a real on-chain value (vs. a 0n placeholder). */\n getBalance: boolean;\n /** `getTransactionReceipt` returns a real RPC response. */\n getTransactionReceipt: boolean;\n /** Calling `requestAccounts` will actually do something — either\n * prompt the user (EIP-2255) or refresh the exposed list. */\n requestAccounts: boolean;\n /** `sendTx` / `sendTxToChain` will work. False for SVM wallets that\n * don't advertise `solana:signAndSendTransaction`. */\n sendTransaction: boolean;\n /** `signIn` works — Sign In With Solana (`solana:signIn`). True only\n * for SVM wallets advertising the feature. */\n signIn: boolean;\n /** `signMessage` will work. False for SVM wallets that don't\n * advertise `solana:signMessage`. */\n signMessage: boolean;\n /** `signTransaction` returns a signed-but-unbroadcast transaction the\n * consumer submits with their own RPC client. True only for SVM\n * wallets advertising `solana:signTransaction`; butr ships no RPC so\n * it can't broadcast the result itself. EVM/hardware adapters leave\n * this `false` (no `signTransaction` method). */\n signTransaction: boolean;\n /** Wallet emits account/chain change events that butr can bridge. */\n subscribe: boolean;\n /** `switchAccount` is real. Almost always `false` for auto adapters\n * — neither protocol exposes silent account switch. Hand-rolled\n * adapters with custom transports may set it `true`. */\n switchAccount: boolean;\n /** `switchChain` routes subsequent calls through the new chain. EVM:\n * true via `wallet_switchEthereumChain`. SVM: true (local state +\n * per-call `chain` input) when more than one chain is advertised. */\n switchChain: boolean;\n};\n\n/**\n * Orchestration interface — what `butr` actually calls during the\n * connect / disconnect / hydrate flow. This is the contract `butr`\n * cares about; everything else on `WalletAdapter` is consumer-facing.\n */\ntype Connector<P extends ChainPlatform = ChainPlatform> = {\n /** Runtime capability flags — see `WalletCapabilities`. Read these\n * to gate UI affordances rather than probing for method existence. */\n capabilities: WalletCapabilities;\n /** Discriminant: which chain platform this adapter speaks. Generic\n * parameter `P` narrows this to a specific platform when consumers\n * use one of the per-platform adapter types (`EvmAdapter`,\n * `SvmAdapter`, etc). */\n chainPlatform: P;\n /** Begin a connection request. Resolves when the wallet is connected,\n * rejects on user cancellation or other error.\n *\n * `opts.silent` requests a non-interactive reconnect to\n * already-authorized accounts — butr's mount-time hydration passes it\n * so a reload restores wallets without re-prompting (Wallet Standard\n * `standard:connect`'s `silent` input; the `eth_accounts` read on\n * EIP-1193). Adapters that can't reconnect without a prompt should\n * reject when `silent` is set rather than show UI; hydration treats\n * the rejection as a clean restore failure. */\n connect: (opts?: { silent?: boolean }) => Promise<void>;\n /** Optional teardown. butr calls this on disconnect, error recovery, and reset. */\n disconnect?: () => Promise<void>;\n /** Read the currently-active account. butr uses this to populate the pool\n * after a successful `connect()` and during hydration. */\n getAccount: () => Promise<Account | null>;\n /** Optional. List every account the wallet exposes. Some browser wallets\n * show many accounts at once (MetaMask with multiple imports). If\n * omitted, butr defaults to `[await getAccount()]`. */\n getAccounts?: () => Promise<Array<Account>>;\n /** Optional. Wallet logo as a URL or data URI. Adapters built via butr's\n * auto-discovery (EIP-6963, Wallet Standard) populate this from the\n * wallet's announced metadata; hand-rolled adapters can leave it\n * unset and supply icons separately via `ConnectorMeta`. */\n icon?: string;\n /** Stable key: \"metamask\", \"phantom\", etc. Pool entries are keyed by this. */\n id: string;\n /** Human name: \"MetaMask\", \"Phantom\", etc. UI-facing only. */\n name: string;\n /** Optional. Ask the wallet to open its account-selection UI so the\n * user can expose additional accounts to this app. Implemented on\n * EIP-6963 wallets via `wallet_requestPermissions`; Wallet Standard\n * wallets generally leave this unset because the user enables more\n * accounts directly in the extension. Resolution doesn't include the\n * new accounts — call `getAccounts()` (or use butr's\n * `useRequestAccounts` hook, which refreshes the pool entry for\n * you). */\n requestAccounts?: () => Promise<void>;\n /** Optional. Subscribe to wallet-side events (account swap, network swap,\n * external disconnect). butr's runtime calls this after a successful\n * `connect()`, and uses the returned function to unsubscribe on\n * disconnect / reset. Bridges native wallet events into the reducer so\n * consumers don't have to wire `accountsChanged` / `chainChanged`\n * themselves. */\n subscribe?: (listener: (event: ConnectorEvent) => void) => () => void;\n};\n\n/**\n * Methods every connected wallet supports regardless of chain. The\n * per-platform `Wallet` types extend this with their platform-specific\n * methods (`signIn` for SVM, `signTransaction` for sign-only paths).\n */\ntype WalletBase = {\n /** Read a token balance. `mint` is optional; the connector decides\n * what \"no mint\" means for its chain (native ETH on EVM, native SOL\n * on Solana, etc.). */\n getBalance: (mint?: string) => Promise<Balance>;\n /** Returns a chain-specific signer. Consumers cast to the concrete\n * type via the `SignerForPlatform` registry (or directly to the\n * library shape they wrap — `WalletClient` on viem, etc.). */\n getSigner: () => Promise<unknown>;\n /** Look up the status of a previously-submitted transaction. */\n getTransactionReceipt: (tx: string) => Promise<{\n status: \"Success\" | \"Error\" | \"Pending\";\n }>;\n /** Submit a transaction on the wallet's currently-active chain.\n * Pass an `account` from `ConnectedWallet.accounts` to route the\n * transaction through a specific exposed address instead of the\n * wallet's currently-active one. EVM wallets honour this via\n * `tx.from`; Wallet Standard wallets via the feature's `account`\n * input. Omit for \"use whichever the wallet picks.\" */\n sendTx: (tx: unknown, account?: Account) => Promise<string>;\n /** Submit a transaction targeting a specific chain. The optional\n * callback fires after the connector has switched chain (consumers\n * use this to re-enable UI). Pass an `account` to route through a\n * specific exposed address (see `sendTx`). */\n sendTxToChain: (\n tx: unknown,\n targetChainId: string,\n account?: Account,\n cb?: () => void,\n ) => Promise<string>;\n /**\n * Sign a message and return both the signature and the bytes the wallet\n * actually signed. Solana Wallet Standard wallets may prefix or re-encode\n * the message internally; verifiers must check the signature against\n * `signedMessage`, not the input bytes. EVM wallets echo the input.\n *\n * Pass an `account` to sign with a specific exposed address. EIP-1193\n * routes it through `personal_sign`'s address param; Wallet Standard\n * uses the feature's `account` input. Both support per-call signing\n * without changing the wallet's active account.\n */\n signMessage: (\n msg: Uint8Array,\n account?: Account,\n ) => Promise<{ signature: Uint8Array; signedMessage: Uint8Array }>;\n /** Switch to a different account on the same wallet (some wallets\n * expose multiple accounts simultaneously). */\n switchAccount?: (address: string) => Promise<void>;\n /** Switch the wallet's active chain. */\n switchChain: (chain: ChainBase) => Promise<void>;\n};\n\n/**\n * EVM wallet surface. No `signIn` (Sign-In-With-Ethereum is an app-level\n * concern in this library, not a protocol method). No `signTransaction`\n * — EVM wallets sign-and-send via `eth_sendTransaction`; sign-only EVM\n * flows aren't exposed through this surface.\n */\ntype EvmWallet = WalletBase;\n\n/**\n * Solana wallet surface. Adds:\n * - `signIn` — Sign-In-With-Solana (`solana:signIn`). Optional;\n * `capabilities.signIn` gates availability at runtime.\n * - `signTransaction` — sign-only path for wallets that advertise\n * `solana:signTransaction` but not `solana:signAndSendTransaction`.\n * Optional; `capabilities.signTransaction` gates availability.\n */\ntype SvmWallet = WalletBase & {\n /** Sign In With Solana (SIWS, `solana:signIn`). Authenticates the user\n * and returns the connected account plus the signed statement so the\n * consumer can verify server-side. `input` is the SIWS message fields\n * (domain, statement, nonce, …) — pass `{}` or omit for wallet\n * defaults. */\n signIn?: (input?: Record<string, unknown>) => Promise<{\n account: Account;\n signature: Uint8Array;\n signedMessage: Uint8Array;\n }>;\n /** Sign a Solana transaction WITHOUT broadcasting it. butr ships no\n * RPC, so the consumer broadcasts the returned bytes via\n * `@solana/kit` / `@solana/web3.js` / etc. */\n signTransaction?: (tx: unknown, account?: Account) => Promise<Uint8Array>;\n};\n\n/**\n * Sui wallet surface. Adds optional `signTransaction` for the\n * `sui:signTransaction` (sign-only) feature; broadcast is on the\n * consumer via `@mysten/sui`'s SuiClient.\n */\ntype SuiWallet = WalletBase & {\n signTransaction?: (tx: unknown, account?: Account) => Promise<Uint8Array>;\n};\n\n/**\n * Bitcoin wallet surface. `signTransaction` here is `bitcoin:signPsbt`\n * (sign-only PSBT path). Consumers pass `psbt.toBuffer()` bytes; the\n * wallet returns the signed PSBT bytes for the consumer to finalise /\n * broadcast through their own Esplora / Electrum client.\n */\ntype BitcoinWallet = WalletBase & {\n signTransaction?: (tx: unknown, account?: Account) => Promise<Uint8Array>;\n};\n\n/**\n * Polkadot/Substrate wallet surface. No standalone `signTransaction`:\n * building an extrinsic needs chain metadata (an RPC round-trip butr\n * doesn't ship), so transaction signing happens through the\n * `getSigner()` handoff — the consumer builds and submits with the\n * wallet's signer (e.g. polkadot-api). Message signing works via the\n * injected `signer.signRaw`. Same shape as `EvmWallet`.\n */\ntype PolkadotWallet = WalletBase;\n\n/** Per-platform full adapter shapes — `Connector` + the platform's\n * `Wallet` surface. These are the discriminated-union variants of\n * `WalletAdapter`. */\ntype EvmAdapter = Connector<\"evm\"> & EvmWallet;\ntype SvmAdapter = Connector<\"svm\"> & SvmWallet;\ntype SuiAdapter = Connector<\"sui\"> & SuiWallet;\ntype BitcoinAdapter = Connector<\"bitcoin\"> & BitcoinWallet;\ntype PolkadotAdapter = Connector<\"polkadot\"> & PolkadotWallet;\n\n/**\n * Full adapter interface — discriminated union by `chainPlatform`.\n *\n * Narrow on `wallet.connector.chainPlatform === \"svm\"` (etc.) to gain\n * access to platform-specific methods like `signIn` (SVM) or\n * `signTransaction` (SVM / Sui / Bitcoin). Calling those methods on a\n * non-narrowed `WalletAdapter` is a TypeScript error — that's the\n * point. The discriminant carries the type-level fact \"this method\n * doesn't exist on EVM\" so consumers can't accidentally branch on\n * `capabilities.signIn` and call a method that EVM adapters don't\n * implement.\n *\n * Runtime gating via `capabilities` still matters for the methods that\n * are OPTIONAL within a platform (a Solana wallet might or might not\n * advertise `solana:signTransaction`). Capabilities narrow \"wallet\n * supports this feature\"; the discriminated union narrows \"this\n * platform has this concept at all\".\n */\ntype WalletAdapter = EvmAdapter | SvmAdapter | SuiAdapter | BitcoinAdapter | PolkadotAdapter;\n\n/** Deprecated. Use one of the per-platform `*Wallet` types or\n * `WalletBase`. Retained as an alias so existing names resolve. */\ntype Wallet = WalletBase;\n\ntype ConnectedWallet = {\n /** Currently-active account on this wallet. */\n account: Account;\n /** All accounts known on this wallet at the time of connect/refresh.\n * Always contains at least `account`. Populated from `getAccounts()`\n * if the connector implements it; otherwise `[account]`. */\n accounts: Array<Account>;\n connector: WalletAdapter;\n};\n\ntype ConnectorMeta = {\n /** Optional. Sync probe that reports whether the wallet is currently\n * available. Defaults to `\"installed\"` when omitted. Consumers call\n * this at render time to gate the \"Connect\" button. */\n availability?: () => WalletAvailability;\n chainPlatform: ChainPlatform;\n /** Optional image URL or data URI for wallet selection UIs. */\n icon?: string;\n id: string;\n name: string;\n /** Optional. Where to send users who don't have this wallet (download\n * page, app store link, etc.). */\n url?: string;\n};\n\n/**\n * Outcome of butr's mount-time hydration pass. Passed to\n * `WalletManagerConfig.onHydrated`. Three buckets:\n *\n * - `restoredIds` — wallets that came back fully. Their pool entries\n * are live and consumers can use them immediately.\n * - `pendingIds` — wallets whose adapter wasn't registered yet\n * (auto-discovery's async warmup). The runtime retries each one\n * when discovery announces a matching id, so most of these will\n * restore within a few hundred ms of mount.\n * - `dropped` — wallets whose restore actually failed (connector\n * threw mid-flight). These have been removed from storage; consumer\n * UX can surface \"Couldn't reconnect Phantom — connect again.\"\n */\ntype HydrationOutcome = {\n dropped: Array<{ connectorId: string; reason: unknown }>;\n pendingIds: Array<string>;\n restoredIds: Array<string>;\n};\n\ntype WalletManagerConfig = {\n /** Available connector metadata */\n connectors: Array<ConnectorMeta>;\n /** Function to instantiate a connector by ID */\n createConnector: (id: string) => WalletAdapter | null;\n /**\n * Seed the store synchronously with persisted wallet state — typically\n * the return value of `readWalletSnapshot(cookies, { keyPrefix })`\n * called from a Server Component. When provided:\n * - `pool` is populated with `ConnectedWallet` entries whose\n * `connector` is a shadow adapter (see `createShadowAdapter`):\n * identity-only, all capabilities `false`, methods throw\n * `ShadowConnectorError` if called.\n * - `activeConnectorId` and `selection` are set from the snapshot.\n * - `isHydrated` flips `true` immediately on construction.\n * - Every seeded id appears in `reconnectingIds`; the background\n * silent-reconnect pass removes the id and replaces the pool\n * entry with a live adapter on success, or drops the entry on\n * failure.\n *\n * Pre-hydration UI renders from the snapshot's data (address,\n * accounts, chain, name, icon) without a flash. Action affordances\n * (sign, send) are naturally gated by the shadow's all-false\n * capabilities — or consumers can branch on `reconnectingIds`.\n */\n initialState?: WalletSnapshot;\n /** Called after a wallet is successfully connected */\n onConnect?: (wallet: ConnectedWallet) => void;\n /**\n * Called after a connection attempt fails (user rejected, wallet\n * locked, chain mismatch, timeout, …). Receives the normalised\n * `ConnectionError` plus the id of the connector that was being\n * connected. Useful for piping into observability tooling\n * (Sentry, OTel) without each consumer wiring `try/catch`s around\n * `connectWallet` themselves.\n */\n onConnectError?: (error: ConnectionError, connectorId: string) => void;\n /** Called after a wallet is disconnected */\n onDisconnect?: (chainPlatform: ChainPlatform) => void;\n /**\n * Called once after butr's mount-time hydration finishes. Receives a\n * `HydrationOutcome` summarising which stored wallets were restored,\n * which are pending an adapter announcement, and which failed.\n * Useful for surfacing \"Phantom couldn't be reconnected — try\n * again\" UX or piping a metric to telemetry.\n */\n onHydrated?: (outcome: HydrationOutcome) => void;\n /** Called after all wallets are reset (e.g., to clear auth tokens) */\n onReset?: () => void | Promise<void>;\n /**\n * Called when a connect attempt takes longer than\n * `slowConnectThresholdMs` (default 5_000) but hasn't yet resolved\n * or rejected. Fires at most once per connect attempt. Useful for\n * surfacing a \"still trying — check your wallet\" hint in the UI or\n * piping a slow-path metric to telemetry.\n */\n onSlowConnect?: (connectorId: string) => void;\n /**\n * Called when a storage write fails. butr's persistence layer is\n * fire-and-forget by design (any individual write can fail without\n * breaking butr's reducer state), but the consumer might still want\n * to know — quota-exceeded errors, IndexedDB shutdown, cross-tab\n * conflicts, cookie size limits. `context` is a short string\n * describing which write failed (e.g. `\"failed to persist pool\"`).\n * The default behaviour when no callback is set is `console.warn`.\n */\n onStorageError?: (error: unknown, context: string) => void;\n /** Threshold for `onSlowConnect`, in milliseconds. Defaults to 5_000. */\n slowConnectThresholdMs?: number;\n /** Optional custom persistence implementation (e.g., cookie-backed) */\n storage?: WalletPersistence;\n /** Storage key prefix for localStorage */\n storageKeyPrefix?: string;\n};\n\nexport { CHAIN_PLATFORMS };\n\nexport type {\n Account,\n Balance,\n BitcoinAdapter,\n BitcoinWallet,\n ChainPlatform,\n ConnectedWallet,\n Connector,\n ConnectorEvent,\n ConnectorMeta,\n EvmAdapter,\n EvmWallet,\n HydrationOutcome,\n PolkadotAdapter,\n PolkadotWallet,\n SuiAdapter,\n SuiWallet,\n SvmAdapter,\n SvmWallet,\n Wallet,\n WalletAdapter,\n WalletAvailability,\n WalletBase,\n WalletCapabilities,\n WalletManagerConfig,\n};\n","import type { WalletAdapter } from \"./types\";\n\n/**\n * A discovery seam. Implementations call `onAdapter(adapter)` each time\n * they find a wallet and return an unsubscribe handle. `@usebutr/wallets`\n * composes EVM + SVM into a single `WalletSource`; third parties can\n * implement this type without depending on `@usebutr/wallets`.\n */\ntype WalletSource = {\n subscribe: (onAdapter: (adapter: WalletAdapter) => void) => () => void;\n};\n\n/**\n * Wrap a bare `subscribe` function (the exact shape of\n * `discoverEvmAdapters` / `discoverSvmAdapters`) into a `WalletSource`,\n * so an EVM-only app can do\n * `createWalletSource(discoverEvmAdapters)` without importing anything\n * protocol-bearing beyond `@usebutr/evm`.\n */\nconst createWalletSource = (\n subscribe: (onAdapter: (adapter: WalletAdapter) => void) => () => void,\n): WalletSource => ({ subscribe });\n\nexport type { WalletSource };\nexport { createWalletSource };\n","/* eslint-disable no-console -- central logging sink; the one sanctioned console use */\nconst logWarn = (...args: ReadonlyArray<unknown>): void => {\n console.warn(...args);\n};\n\nconst logError = (...args: ReadonlyArray<unknown>): void => {\n console.error(...args);\n};\n/* eslint-enable no-console */\n\nexport { logError, logWarn };\n","import type { StorageDriver } from \"./persistence\";\n\ntype BrowserStorageDrivers = {\n /** Survives app restart (localStorage on web, AsyncStorage/MMKV on RN). */\n persistent: StorageDriver;\n /** Cleared when the app session ends (sessionStorage on web, in-memory on RN). */\n session: StorageDriver;\n};\n\ntype WebStorageKind = \"localStorage\" | \"sessionStorage\";\n\nconst hasWebStorage = (kind: WebStorageKind): boolean => {\n try {\n return (\n typeof globalThis !== \"undefined\" &&\n (globalThis as Record<string, unknown>)[kind] !== undefined\n );\n } catch {\n return false;\n }\n};\n\nconst createMemoryStorageDriver = (): StorageDriver => {\n const memory = new Map<string, string>();\n return {\n getItem(key) {\n return memory.get(key) ?? null;\n },\n removeItem(key) {\n memory.delete(key);\n },\n setItem(key, value) {\n memory.set(key, value);\n },\n };\n};\n\nconst createWebStorageDriver = (kind: WebStorageKind): StorageDriver => {\n if (!hasWebStorage(kind)) {\n return createMemoryStorageDriver();\n }\n\n const storage = (globalThis as unknown as Record<WebStorageKind, Storage>)[kind];\n\n return {\n getItem(key) {\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n },\n removeItem(key) {\n try {\n storage.removeItem(key);\n } catch {\n // ignore\n }\n },\n setItem(key, value) {\n try {\n storage.setItem(key, value);\n } catch {\n // ignore quota/security errors\n }\n },\n };\n};\n\n/**\n * Default storage drivers for web. `persistent` wraps `localStorage`,\n * `session` wraps `sessionStorage`. Both fall back to in-memory maps\n * when the global isn't available (SSR, non-browser environments).\n */\nconst createBrowserStorageDriver = (): BrowserStorageDrivers => ({\n persistent: createWebStorageDriver(\"localStorage\"),\n session: createWebStorageDriver(\"sessionStorage\"),\n});\n\nexport type { BrowserStorageDrivers };\nexport { createBrowserStorageDriver, createMemoryStorageDriver };\n","import { logWarn } from \"../logger\";\nimport { CHAIN_PLATFORMS } from \"../types\";\nimport type { ChainPlatform, ConnectedWallet } from \"../types\";\n\nimport { createBrowserStorageDriver } from \"./browser-storage-driver\";\nimport type {\n StorageDriver,\n StoredPoolEntry,\n StoredPoolRecord,\n StoredSelectionRecord,\n WalletPersistence,\n} from \"./persistence\";\n\nconst VALID_CHAIN_PLATFORMS = new Set<ChainPlatform>(CHAIN_PLATFORMS);\n\ntype StorageConfig = {\n keyPrefix: string;\n /** Survives app restart. Defaults to localStorage on web. */\n persistent?: StorageDriver;\n /** Cleared on session end. Defaults to sessionStorage on web. */\n session?: StorageDriver;\n};\n\nconst isValidAccount = (value: unknown): boolean => {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const account = value as Record<string, unknown>;\n if (typeof account.walletAddress !== \"string\" || typeof account.id !== \"string\") {\n return false;\n }\n if (!account.chain || typeof account.chain !== \"object\") {\n return false;\n }\n return true;\n};\n\n/**\n * Structural validator for a serialized pool entry.\n *\n * Used in two directions:\n * - On read (`getPool`): malformed entries from storage are warned\n * and dropped — legacy / cross-tab corruption shouldn't crash the\n * consumer.\n * - On write (`setPool`): the runtime's reducer state is the source\n * of truth, and a malformed write would indicate a programming\n * error inside butr. Throw rather than silently corrupt storage.\n *\n * Same validator either way — keeping the two paths symmetric means\n * \"what's storable\" is a single fact.\n */\nconst isValidPoolEntry = (key: string, value: unknown): value is StoredPoolEntry => {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const entry = value as Record<string, unknown>;\n if (typeof entry.connectorId !== \"string\" || entry.connectorId !== key) {\n return false;\n }\n if (typeof entry.chainPlatform !== \"string\") {\n return false;\n }\n if (!VALID_CHAIN_PLATFORMS.has(entry.chainPlatform as ChainPlatform)) {\n return false;\n }\n if (typeof entry.name !== \"string\" || entry.name.length === 0) {\n return false;\n }\n // `icon` is optional (some adapters announce no icon); reject only\n // when present-but-wrong-typed.\n if (entry.icon !== undefined && typeof entry.icon !== \"string\") {\n return false;\n }\n if (!isValidAccount(entry.account)) {\n return false;\n }\n if (!Array.isArray(entry.accounts) || !entry.accounts.every(isValidAccount)) {\n return false;\n }\n return true;\n};\n\nclass WalletStorage implements WalletPersistence {\n private poolKey: string;\n private selectionKey: string;\n private activeKey: string;\n private userDisconnectedKey: string;\n private persistent: StorageDriver;\n private session: StorageDriver;\n /**\n * Serializes pool-key mutations so concurrent fire-and-forget\n * writes can't interleave their read-modify-write phases. Without\n * this, two simultaneous `setPool` calls both read the pre-write\n * state, each merge their own entries, and whichever finishes last\n * overwrites the other's additions. Reads (`getPool`) don't enter\n * the queue — they observe whatever's currently in the driver.\n */\n private poolMutationQueue: Promise<unknown> = Promise.resolve();\n\n constructor(config: StorageConfig) {\n this.poolKey = `${config.keyPrefix}-pool`;\n this.selectionKey = `${config.keyPrefix}-selection`;\n this.activeKey = `${config.keyPrefix}-active`;\n this.userDisconnectedKey = `${config.keyPrefix}-user-disconnected`;\n\n if (config.persistent && config.session) {\n this.persistent = config.persistent;\n this.session = config.session;\n } else {\n const defaults = createBrowserStorageDriver();\n this.persistent = config.persistent ?? defaults.persistent;\n this.session = config.session ?? defaults.session;\n }\n }\n\n /** Chain `fn` after the in-flight pool mutation. */\n private async serializePoolMutation<T>(fn: () => Promise<T>): Promise<T> {\n // Capture and advance the queue synchronously so concurrent\n // callers serialize against the same head — awaiting the queue\n // first would let two callers both observe the pre-advance head\n // and run in parallel.\n const previous = this.poolMutationQueue;\n // oxlint-disable-next-line unicorn/consistent-function-scoping -- assigned by Promise constructor below\n let resolve: () => void = () => {};\n this.poolMutationQueue = new Promise<void>((r) => {\n resolve = r;\n });\n try {\n await previous;\n } catch {\n // Previous mutation's failure shouldn't jam the queue — each\n // call site already observes its own rejection.\n }\n try {\n return await fn();\n } finally {\n resolve();\n }\n }\n\n // ---- Pool ----\n\n async getPool(): Promise<StoredPoolRecord> {\n try {\n const stored = await this.persistent.getItem(this.poolKey);\n if (!stored) {\n return {};\n }\n const parsed: unknown = JSON.parse(stored);\n if (!parsed || typeof parsed !== \"object\") {\n await this.clearPool();\n return {};\n }\n const result: StoredPoolRecord = {};\n for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {\n if (isValidPoolEntry(key, value)) {\n result[key] = value;\n } else {\n logWarn(`[butr] dropping invalid pool entry for ${key}`);\n }\n }\n return result;\n } catch (error) {\n logWarn(\"[butr] failed to parse pool from storage:\", error);\n await this.clearPool();\n return {};\n }\n }\n\n /**\n * Upsert the in-memory pool into storage. Additive: entries in\n * `pool` are written; entries already in storage that aren't in\n * `pool` are kept. The in-memory pool reflects \"what's live right\n * now\", not \"the complete list of remembered connections\" — a\n * silent reconnect that fails on reload leaves the entry out of\n * the pool but the saved entry stays so the next load can retry.\n * Use `removePoolEntry` for explicit eviction (the user clicked\n * Disconnect) and `clearAll` for a full wipe (reset).\n */\n setPool(pool: Map<string, ConnectedWallet>): Promise<void> {\n return this.serializePoolMutation(async () => {\n try {\n const existing = await this.getPool();\n const serializable: StoredPoolRecord = { ...existing };\n for (const [connectorId, wallet] of pool) {\n const entry: StoredPoolEntry = {\n account: wallet.account,\n accounts: wallet.accounts,\n chainPlatform: wallet.connector.chainPlatform,\n connectorId,\n icon: wallet.connector.icon,\n name: wallet.connector.name,\n };\n // The runtime's reducer state is the source of truth — a\n // malformed entry here means a programming error inside butr,\n // not data drift. Throw loudly so the bug surfaces at the\n // write site rather than silently corrupting storage and\n // re-emerging as a \"wallet didn't restore\" puzzle on the next\n // page load.\n if (!isValidPoolEntry(connectorId, entry)) {\n throw new Error(`[butr] refusing to persist invalid pool entry for ${connectorId}`);\n }\n serializable[connectorId] = entry;\n }\n await this.persistent.setItem(this.poolKey, JSON.stringify(serializable));\n } catch (error) {\n logWarn(\"[butr] failed to persist pool:\", error);\n }\n });\n }\n\n removePoolEntry(connectorId: string): Promise<void> {\n return this.serializePoolMutation(async () => {\n try {\n const stored = await this.getPool();\n if (stored[connectorId]) {\n const { [connectorId]: _, ...remaining } = stored;\n await this.persistent.setItem(this.poolKey, JSON.stringify(remaining));\n }\n } catch (error) {\n logWarn(`[butr] failed to remove pool entry ${connectorId}:`, error);\n }\n });\n }\n\n clearPool(): Promise<void> {\n return this.serializePoolMutation(async () => {\n await this.persistent.removeItem(this.poolKey);\n });\n }\n\n // ---- Selection ----\n\n async getSelection(): Promise<StoredSelectionRecord> {\n try {\n const stored = await this.persistent.getItem(this.selectionKey);\n if (!stored) {\n return {};\n }\n const parsed: unknown = JSON.parse(stored);\n if (!parsed || typeof parsed !== \"object\") {\n return {};\n }\n const result: StoredSelectionRecord = {};\n for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {\n if (\n VALID_CHAIN_PLATFORMS.has(key as ChainPlatform) &&\n typeof value === \"string\" &&\n value.length > 0\n ) {\n result[key as ChainPlatform] = value;\n }\n }\n return result;\n } catch (error) {\n logWarn(\"[butr] failed to parse selection from storage:\", error);\n return {};\n }\n }\n\n async setSelection(selection: Map<ChainPlatform, string>): Promise<void> {\n try {\n const serializable: StoredSelectionRecord = {};\n for (const [platform, connectorId] of selection) {\n serializable[platform] = connectorId;\n }\n await this.persistent.setItem(this.selectionKey, JSON.stringify(serializable));\n } catch (error) {\n logWarn(\"[butr] failed to persist selection:\", error);\n }\n }\n\n // ---- Active connector ----\n\n async getActiveConnectorId(): Promise<string | null> {\n try {\n const value = await this.persistent.getItem(this.activeKey);\n return value && value.length > 0 ? value : null;\n } catch {\n return null;\n }\n }\n\n async setActiveConnectorId(connectorId: string | null): Promise<void> {\n try {\n await (connectorId === null\n ? this.persistent.removeItem(this.activeKey)\n : this.persistent.setItem(this.activeKey, connectorId));\n } catch (error) {\n logWarn(\"[butr] failed to persist active connector id:\", error);\n }\n }\n\n // ---- Bulk clear ----\n\n async clearAll(): Promise<void> {\n // Pool removal goes through the mutation queue so it can't race\n // with an in-flight `setPool` / `removePoolEntry`. The selection\n // and active keys have no read-modify-write writers, so they can\n // remove concurrently.\n await Promise.all([\n this.clearPool(),\n this.persistent.removeItem(this.selectionKey),\n this.persistent.removeItem(this.activeKey),\n ]);\n }\n\n // ---- Disconnect intent ----\n\n /**\n * Disconnect-intent tracking.\n *\n * Lives in the session driver: survives component remounts (unlike refs)\n * but clears when the session ends (unlike the persistent driver).\n * Prevents auto-connect from firing immediately after a manual disconnect,\n * while still allowing auto-connect on fresh sessions.\n */\n async isUserDisconnected(): Promise<boolean> {\n try {\n const value = await this.session.getItem(this.userDisconnectedKey);\n return value === \"true\";\n } catch {\n return false;\n }\n }\n\n async markUserDisconnected(value: boolean): Promise<void> {\n try {\n await (value\n ? this.session.setItem(this.userDisconnectedKey, \"true\")\n : this.session.removeItem(this.userDisconnectedKey));\n } catch {\n // ignore\n }\n }\n}\n\nexport { WalletStorage };\n","import { logWarn } from \"../logger\";\nimport type { Account, ChainPlatform, Connector } from \"../types\";\n\n/**\n * Side-effect callbacks the lifecycle bridge invokes when the\n * underlying wallet emits an event. The bridge owns event-to-action\n * mapping and the unsubscribe handle; the runtime owns what those\n * actions actually do (dispatch reducer events, persist, notify\n * consumer callbacks).\n */\ntype LifecycleHandlers = {\n /** Wallet exposed a new accounts list (or active account swap). The\n * bridge forwards the full array — single-account wallets included.\n * `active` is the address the wallet picked as current. */\n onAccountChanged: (\n connectorId: string,\n accounts: ReadonlyArray<Account>,\n active: Account,\n ) => void;\n /** Wallet disconnected externally (user locked, extension removed,\n * WC session ended on the relay). The bridge has already cleared\n * the subscription for `connectorId` by the time this fires. */\n onDisconnected: (connectorId: string, chainPlatform: ChainPlatform) => void;\n};\n\n/**\n * Owns the \"exactly one subscription per connector\" invariant plus the\n * event-to-handler choreography. Replaces three previously-scattered\n * call sites in the runtime (`hydrate`, `tryRestoreFromPending`,\n * `connectWallet`) and the matching teardown sites\n * (`disconnectWallet`, `reset`, the disconnect-event handler).\n */\ntype ConnectorLifecycle = {\n /**\n * Subscribe to the connector's events. Idempotent — calling `attach`\n * twice for the same `connectorId` detaches the previous subscription\n * before installing the new one, preserving the \"exactly one\"\n * invariant. No-op for connectors without a `subscribe` method.\n */\n attach: (connectorId: string, connector: Connector) => void;\n /** Detach a single connector. Safe to call when no subscription is\n * registered. */\n detach: (connectorId: string) => void;\n /** Detach every active subscription. Used during `reset`. */\n detachAll: () => void;\n};\n\nconst createConnectorLifecycle = (handlers: LifecycleHandlers): ConnectorLifecycle => {\n // Private to the bridge — the runtime never reads or writes this Map.\n const unsubscribers = new Map<string, () => void>();\n\n const detach = (connectorId: string) => {\n const unsub = unsubscribers.get(connectorId);\n if (!unsub) {\n return;\n }\n try {\n unsub();\n } catch (error: unknown) {\n logWarn(\"[butr] unsubscribe threw:\", error);\n }\n unsubscribers.delete(connectorId);\n };\n\n return {\n attach: (connectorId, connector) => {\n if (!connector.subscribe) {\n return;\n }\n // Idempotent install — drop any prior subscription first so a\n // re-attach doesn't leak listeners on the wallet side.\n detach(connectorId);\n try {\n const unsub = connector.subscribe((event) => {\n switch (event.type) {\n case \"accountChanged\": {\n handlers.onAccountChanged(connectorId, event.accounts, event.account);\n break;\n }\n case \"disconnected\": {\n // Clear the subscription before notifying so the handler\n // sees a clean state and can't re-enter via dispatch\n // chains.\n detach(connectorId);\n handlers.onDisconnected(connectorId, connector.chainPlatform);\n break;\n }\n default: {\n const exhaustiveCheck: never = event;\n void exhaustiveCheck;\n }\n }\n });\n unsubscribers.set(connectorId, unsub);\n } catch (error: unknown) {\n logWarn(`[butr] subscribe failed for ${connectorId}:`, error);\n }\n },\n\n detach,\n\n detachAll: () => {\n // Snapshot keys before iterating because `detach` mutates the Map.\n const ids: Array<string> = [];\n for (const id of unsubscribers.keys()) {\n ids.push(id);\n }\n for (const id of ids) {\n detach(id);\n }\n },\n };\n};\n\nexport type { ConnectorLifecycle, LifecycleHandlers };\nexport { createConnectorLifecycle };\n","import type { StoredPoolEntry, WalletPersistence } from \"../storage\";\nimport type {\n Account,\n ChainPlatform,\n ConnectedWallet,\n Connector,\n WalletManagerConfig,\n} from \"../types\";\n\n/**\n * Restore outcome for a single pool entry. `kind: \"ok\"` carries the\n * fully-formed `ConnectedWallet`. `kind: \"fail\"` carries the raw error\n * so the caller can route it to telemetry.\n */\ntype RestoreOutcome =\n | { connectorId: string; entry: ConnectedWallet; kind: \"ok\" }\n | { connectorId: string; error: unknown; kind: \"fail\" };\n\n/**\n * Snapshot returned by `HydrationCoordinator.hydrate()` — everything\n * the reducer needs to compose a `HYDRATED` event plus the metadata the\n * runtime uses to wire subscriptions and surface the outcome.\n */\ntype HydrateResult = {\n activeConnectorId: string | null;\n /** Entries whose restore failed (connect() rejected, the connector\n * threw mid-flight). Reported for telemetry only — storage is\n * preserved so the next load can retry. The most common cause is\n * EIP-1193 `eth_accounts: []` from a locked wallet, which clears as\n * soon as the user unlocks and reloads. */\n dropped: Array<{ connectorId: string; reason: unknown }>;\n isUserDisconnected: boolean;\n /** Entries parked because `createConnector(id)` returned `null` at\n * hydration time (typical for Wallet Standard adapters announced\n * asynchronously). The coordinator keeps an internal record of these\n * and resolves them when the runtime later calls `drainPending`. */\n pendingIds: Array<string>;\n pool: Map<string, ConnectedWallet>;\n selection: Map<ChainPlatform, string>;\n};\n\ntype HydrationCoordinator = {\n /**\n * Restore a parked entry whose adapter has now become available.\n * Returns `null` if no entry is parked under `connectorId`. Returns an\n * `ok` outcome with the new `ConnectedWallet`, or a `fail` outcome\n * with the error (storage cleanup is handled internally).\n */\n drainPending: (connectorId: string) => Promise<RestoreOutcome | null>;\n /**\n * Read storage, instantiate every adapter that's currently\n * registered, restore in parallel, park the rest. After the returned\n * promise resolves, the coordinator holds an internal pending queue\n * indexed by `connectorId`. Resolve queued entries via `drainPending`.\n */\n hydrate: () => Promise<HydrateResult>;\n /**\n * Snapshot of currently-parked ids. The runtime uses this once\n * immediately after `hydrate()` resolves to drain entries whose\n * adapter announced *during* the hydration window (the discovery race\n * we used to resolve manually inside the store).\n */\n pendingIds: () => Array<string>;\n};\n\n/** Pick the right `accounts` list: fresh from the connector if it\n * exposes `getAccounts`, otherwise the persisted list, otherwise just\n * the active account. */\nconst resolveHydratedAccounts = async (\n connector: Connector,\n storedAccounts: ReadonlyArray<Account>,\n fallbackAccount: Account,\n): Promise<Array<Account>> => {\n if (connector.getAccounts) {\n const fresh = await connector.getAccounts().catch(() => null);\n if (fresh && fresh.length > 0) {\n return fresh;\n }\n }\n if (storedAccounts.length > 0) {\n return [...storedAccounts];\n }\n return [fallbackAccount];\n};\n\nconst restoreOneEntry = async (\n connectorId: string,\n entry: { account: Account; accounts: ReadonlyArray<Account> },\n connector: Connector,\n): Promise<RestoreOutcome> => {\n try {\n // Eager restore: ask the wallet to reconnect to already-authorized\n // accounts without prompting (Wallet Standard `silent`, EIP-1193\n // `eth_accounts`). A wallet that can't do this silently rejects;\n // the entry stays out of the pool for this session but storage is\n // preserved so the next load (e.g. once the user unlocks their\n // wallet) can retry. EIP-1193 `eth_accounts: []` is ambiguous\n // between \"locked\" and \"deauthorized\" — dropping the storage entry\n // on a transient `[]` was the cause of the reload-disconnect race.\n await connector.connect({ silent: true });\n const freshAccount = await connector.getAccount();\n const accountToUse = freshAccount || entry.account;\n const accounts = await resolveHydratedAccounts(connector, entry.accounts, accountToUse);\n return {\n connectorId,\n entry: {\n account: accountToUse,\n accounts,\n connector: connector as ConnectedWallet[\"connector\"],\n },\n kind: \"ok\",\n };\n } catch (error) {\n return { connectorId, error, kind: \"fail\" };\n }\n};\n\nconst createHydrationCoordinator = (\n storage: WalletPersistence,\n createConnector: WalletManagerConfig[\"createConnector\"],\n): HydrationCoordinator => {\n // Storage entries only leave on explicit `disconnectWallet`. Failed\n // restores stay parked / reported as `dropped` — they re-attempt on\n // the next hydrate, so a transient `eth_accounts: []` from a locked\n // wallet doesn't permanently erase the connection.\n //\n // Private to the coordinator — the runtime never touches the queue\n // directly. Storing the raw `StoredPoolEntry` is enough; the entry\n // gets re-restored through the same `restoreOneEntry` path used by\n // the eager pass, so the two code paths can't drift.\n const pending = new Map<string, StoredPoolEntry>();\n\n return {\n drainPending: async (connectorId) => {\n const entry = pending.get(connectorId);\n if (!entry) {\n return null;\n }\n const connector = createConnector(connectorId);\n if (!connector) {\n // Adapter still not available — leave the entry parked.\n return null;\n }\n const outcome = await restoreOneEntry(connectorId, entry, connector);\n pending.delete(connectorId);\n return outcome;\n },\n\n hydrate: async () => {\n const [storedPool, storedSelection, storedActive, userDisconnected] = await Promise.all([\n storage.getPool(),\n storage.getSelection(),\n storage.getActiveConnectorId(),\n storage.isUserDisconnected(),\n ]);\n\n const pool = new Map<string, ConnectedWallet>();\n const dropped: Array<{ connectorId: string; reason: unknown }> = [];\n\n // Clear pending from any prior hydrate() in the same coordinator\n // instance (e.g. tests that rehydrate). The runtime only calls\n // hydrate() once per provider mount, but defending against the\n // multi-call case is cheap.\n pending.clear();\n\n // Build the restore-task list eagerly. A null factory result\n // parks the entry; an instantiated connector enters the parallel\n // restore pool.\n const tasks: Array<Promise<RestoreOutcome>> = [];\n for (const [connectorId, entry] of Object.entries(storedPool)) {\n if (!entry) {\n continue;\n }\n const connector = createConnector(connectorId);\n if (!connector) {\n pending.set(connectorId, entry);\n continue;\n }\n tasks.push(restoreOneEntry(connectorId, entry, connector));\n }\n\n const outcomes = await Promise.all(tasks);\n for (const outcome of outcomes) {\n if (outcome.kind === \"ok\") {\n pool.set(outcome.connectorId, outcome.entry);\n continue;\n }\n dropped.push({ connectorId: outcome.connectorId, reason: outcome.error });\n }\n\n // Reconcile selection: drop stale entries, fill platforms with\n // a pool member but no stored selection.\n const selection = new Map<ChainPlatform, string>();\n for (const [platform, connectorId] of Object.entries(storedSelection)) {\n if (connectorId && pool.has(connectorId)) {\n selection.set(platform as ChainPlatform, connectorId);\n }\n }\n for (const [connectorId, wallet] of pool) {\n const platform = wallet.connector.chainPlatform;\n if (!selection.has(platform)) {\n selection.set(platform, connectorId);\n }\n }\n\n let activeConnectorId: string | null = null;\n if (storedActive && pool.has(storedActive)) {\n activeConnectorId = storedActive;\n } else if (pool.size > 0) {\n activeConnectorId = pool.keys().next().value ?? null;\n }\n\n return {\n activeConnectorId,\n dropped,\n isUserDisconnected: userDisconnected,\n pendingIds: [...pending.keys()],\n pool,\n selection,\n };\n },\n\n pendingIds: () => [...pending.keys()],\n };\n};\n\nexport type { HydrateResult, HydrationCoordinator, RestoreOutcome };\nexport { createHydrationCoordinator };\n","import type { Account, ChainPlatform, ConnectedWallet } from \"../types\";\nimport type { ConnectionError } from \"../types/errors\";\n\n/**\n * Public connection-status enum. `state.connectionStatus` in the\n * reducer only takes the first four values (\"idle\" | \"connecting\" |\n * \"success\" | \"error\") — those track the user-initiated connect\n * attempt. The fifth value, `\"reconnecting\"`, is *derived* by\n * `useConnectionStatus` when the active wallet is still backed by a\n * shadow adapter (its id is in `state.reconnectingIds`). The\n * derivation lives in the React selector so the reducer can stay a\n * narrow state machine while the public API matches wagmi's\n * vocabulary.\n */\ntype ConnectionStatus = \"idle\" | \"connecting\" | \"success\" | \"error\" | \"reconnecting\";\n\ntype State = {\n activeConnectorId: string | null;\n connectingConnectorId: string | null;\n connectionError: ConnectionError | null;\n connectionStatus: ConnectionStatus;\n isHydrated: boolean;\n isUserDisconnected: boolean;\n pool: Map<string, ConnectedWallet>;\n /**\n * Connector IDs whose pool entry is currently backed by a shadow\n * adapter — created from `WalletManagerConfig.initialState` and\n * waiting for the live adapter to be announced (via discovery) and\n * the silent reconnect to succeed. The set shrinks as entries\n * upgrade (`HYDRATED` / `CONNECT_SUCCEEDED` clear matching ids) or\n * drop (`DISCONNECTED` / `RESET`). Empty for stores constructed\n * without `initialState`.\n */\n reconnectingIds: ReadonlySet<string>;\n selection: Map<ChainPlatform, string>;\n};\n\n/**\n * Lifecycle events: hydration, full reset, and the explicit\n * user-disconnected flag the runtime sets to suppress eager reconnect.\n */\ntype LifecycleEvent =\n | {\n activeConnectorId: string | null;\n isUserDisconnected: boolean;\n pool: Map<string, ConnectedWallet>;\n selection: Map<ChainPlatform, string>;\n type: \"HYDRATED\";\n }\n | { type: \"RESET\" }\n | { type: \"USER_DISCONNECTED_SET\"; value: boolean };\n\n/**\n * Connection status events: the transitions of the in-flight connect\n * attempt — start, success/failure, status/error reset. None of these\n * mutate the pool directly; `CONNECT_SUCCEEDED` is the bridge to\n * `PoolMutationEvent`.\n */\ntype ConnectionStatusEvent =\n | { connectorId: string; type: \"CONNECT_STARTED\" }\n | { connectorId: string; entry: ConnectedWallet; type: \"CONNECT_SUCCEEDED\" }\n | { error: ConnectionError; type: \"CONNECT_FAILED\" }\n | { error: ConnectionError | null; type: \"ERROR_SET\" }\n | { type: \"STATUS_RESET\" };\n\n/**\n * Pool-mutation events: changes to the set of connected wallets and\n * their per-wallet account lists. `DISCONNECTED` removes an entry;\n * the refresh events update an existing one in-place.\n */\ntype PoolMutationEvent =\n | {\n /** When set, becomes the new active account. Used by paths that\n * know which account should be active (wallet event, manual\n * update). When unset, the reducer preserves the current active\n * if it's still in `accounts`, else picks `accounts[0]`. */\n accounts: Array<Account>;\n active?: Account;\n connectorId: string;\n type: \"ACCOUNTS_REFRESHED\";\n }\n | { connectorId: string; type: \"DISCONNECTED\" }\n | { connectorId: string; type: \"WALLET_REFRESHED\" };\n\n/**\n * Selection events: which connector is active, and which connector\n * serves each chain platform. Pure pointer updates — no pool mutation.\n */\ntype SelectionEvent =\n | { chainPlatform: ChainPlatform; connectorId: string | null; type: \"SELECTION_CHANGED\" }\n | { connectorId: string | null; type: \"ACTIVE_CHANGED\" };\n\n/**\n * The single event type the reducer dispatches on. Grouped above by\n * concern so a reader sees the map before the cases — adding an event\n * means picking the group it belongs to.\n */\ntype Event = ConnectionStatusEvent | LifecycleEvent | PoolMutationEvent | SelectionEvent;\n\nconst initialState: State = {\n activeConnectorId: null,\n connectingConnectorId: null,\n connectionError: null,\n connectionStatus: \"idle\",\n isHydrated: false,\n isUserDisconnected: false,\n pool: new Map(),\n reconnectingIds: new Set(),\n selection: new Map(),\n};\n\n/** Find any connector in the pool serving a given platform. */\nconst findConnectorForPlatform = (\n pool: Map<string, ConnectedWallet>,\n chainPlatform: ChainPlatform,\n): string | undefined => {\n for (const [id, wallet] of pool) {\n if (wallet.connector.chainPlatform === chainPlatform) {\n return id;\n }\n }\n return undefined;\n};\n\n/** Pure reducer: every state transition is expressed as `(state, event) => state`.\n * No I/O, no async, no side effects. Side effects live in the runtime. */\nconst reducer = (state: State, event: Event): State => {\n switch (event.type) {\n case \"HYDRATED\": {\n // Merge instead of replace. CONNECT_SUCCEEDED can fire during the\n // late-restore window — discovery announces an adapter, the runtime\n // calls tryRestoreFromPending, drainPending succeeds, the reducer\n // adds the entry to state.pool — all BEFORE hydrate's outer await\n // resolves and HYDRATED dispatches. A wholesale replace at that\n // point wipes the freshly-restored late entry. Merging keeps both\n // the eager-restored entries (event.pool) and the late-restored\n // entries (state.pool).\n const pool = new Map<string, ConnectedWallet>(state.pool);\n for (const [id, entry] of event.pool) {\n pool.set(id, entry);\n }\n const selection = new Map<ChainPlatform, string>(state.selection);\n for (const [platform, id] of event.selection) {\n selection.set(platform, id);\n }\n // Prefer hydrate's activeConnectorId when valid in the merged\n // pool (matches the pre-reload selection). Fall back to any late-\n // restore-driven active if hydrate's choice didn't restore eagerly.\n let activeConnectorId: string | null = null;\n if (event.activeConnectorId && pool.has(event.activeConnectorId)) {\n activeConnectorId = event.activeConnectorId;\n } else if (state.activeConnectorId && pool.has(state.activeConnectorId)) {\n activeConnectorId = state.activeConnectorId;\n } else if (pool.size > 0) {\n activeConnectorId = pool.keys().next().value ?? null;\n }\n // Clear reconnectingIds for every entry that came back via the\n // event's live-pool. Shadows that weren't upgraded (adapter not\n // yet announced) stay in `state.pool` and stay in\n // `reconnectingIds`; they'll be cleared individually by\n // CONNECT_SUCCEEDED when discovery's late-restore path resolves.\n let nextReconnecting: ReadonlySet<string> = state.reconnectingIds;\n if (state.reconnectingIds.size > 0 && event.pool.size > 0) {\n const next = new Set(state.reconnectingIds);\n for (const id of event.pool.keys()) {\n next.delete(id);\n }\n if (next.size !== state.reconnectingIds.size) {\n nextReconnecting = next;\n }\n }\n return {\n ...state,\n activeConnectorId,\n isHydrated: true,\n isUserDisconnected: event.isUserDisconnected,\n pool,\n reconnectingIds: nextReconnecting,\n selection,\n };\n }\n\n case \"USER_DISCONNECTED_SET\": {\n return { ...state, isUserDisconnected: event.value };\n }\n\n case \"CONNECT_STARTED\": {\n return {\n ...state,\n connectingConnectorId: event.connectorId,\n connectionError: null,\n connectionStatus: \"connecting\",\n };\n }\n\n case \"CONNECT_SUCCEEDED\": {\n const { connectorId, entry } = event;\n const existing = state.pool.get(connectorId);\n\n // Drop the id from reconnectingIds when present. Covers both the\n // late-restore path (discovery announced after the initial seed)\n // and ordinary connects — the latter typically have an empty set\n // so this is a no-op for them.\n const nextReconnecting: ReadonlySet<string> = state.reconnectingIds.has(connectorId)\n ? new Set([...state.reconnectingIds].filter((id) => id !== connectorId))\n : state.reconnectingIds;\n\n // Same connector + same address: only flip the status, keep object refs stable\n // so reactive selectors don't churn.\n if (\n existing &&\n existing.account.walletAddress.toLowerCase() === entry.account.walletAddress.toLowerCase()\n ) {\n return {\n ...state,\n activeConnectorId: connectorId,\n connectingConnectorId: null,\n connectionStatus: \"success\",\n pool:\n // When the existing entry was a shadow, the address may\n // match but the connector reference is the placeholder.\n // Swap in the live entry so subsequent calls don't throw\n // ShadowConnectorError.\n existing.connector === entry.connector\n ? state.pool\n : new Map([...state.pool, [connectorId, entry] as const]),\n reconnectingIds: nextReconnecting,\n };\n }\n\n const newPool = new Map([...state.pool, [connectorId, entry] as const]);\n const newSelection = new Map([\n ...state.selection,\n [entry.connector.chainPlatform, connectorId] as const,\n ]);\n\n return {\n ...state,\n activeConnectorId: connectorId,\n connectingConnectorId: null,\n connectionStatus: \"success\",\n pool: newPool,\n reconnectingIds: nextReconnecting,\n selection: newSelection,\n };\n }\n\n case \"CONNECT_FAILED\": {\n return {\n ...state,\n connectingConnectorId: null,\n connectionError: event.error,\n connectionStatus: \"error\",\n };\n }\n\n case \"DISCONNECTED\": {\n const wallet = state.pool.get(event.connectorId);\n if (!wallet) {\n return state;\n }\n\n const newPool = new Map(state.pool);\n newPool.delete(event.connectorId);\n\n const newSelection = new Map(state.selection);\n const platform = wallet.connector.chainPlatform;\n if (newSelection.get(platform) === event.connectorId) {\n newSelection.delete(platform);\n const fallback = findConnectorForPlatform(newPool, platform);\n if (fallback) {\n newSelection.set(platform, fallback);\n }\n }\n\n const firstId = newPool.keys().next();\n const activeConnectorId =\n state.activeConnectorId === event.connectorId\n ? (firstId.value ?? null)\n : state.activeConnectorId;\n\n const nextReconnecting: ReadonlySet<string> = state.reconnectingIds.has(event.connectorId)\n ? new Set([...state.reconnectingIds].filter((id) => id !== event.connectorId))\n : state.reconnectingIds;\n\n return {\n ...state,\n activeConnectorId,\n pool: newPool,\n reconnectingIds: nextReconnecting,\n selection: newSelection,\n };\n }\n\n case \"ACCOUNTS_REFRESHED\": {\n const wallet = state.pool.get(event.connectorId);\n if (!wallet) {\n return state;\n }\n // Pick the new active address. Three policies in priority order:\n // 1. Explicit `event.active` (wallet event or manual update knows\n // what should be active).\n // 2. Preserve current active if it's still in the new list.\n // 3. Fall back to `accounts[0]` so the pool entry doesn't end up\n // pointing at an address the wallet no longer exposes.\n let nextAccount: Account;\n if (event.active) {\n nextAccount = event.active;\n } else {\n const stillHasCurrent = event.accounts.some(\n (a) =>\n a.walletAddress === wallet.account.walletAddress &&\n a.chain.id === wallet.account.chain.id,\n );\n nextAccount = stillHasCurrent ? wallet.account : (event.accounts[0] ?? wallet.account);\n }\n // No-op short-circuit: when the wallet event echoes the current\n // active and the accounts array hasn't changed shape, skip the\n // Map clone so `useSyncExternalStore` subscribers don't re-render.\n // (Cheap heuristic — equality by reference for `accounts` would\n // miss content changes; we compare by length + address set.)\n const sameAccount =\n nextAccount.walletAddress === wallet.account.walletAddress &&\n nextAccount.chain.id === wallet.account.chain.id;\n const sameAccountsShape =\n event.accounts.length === wallet.accounts.length &&\n event.accounts.every((a, i) => a.walletAddress === wallet.accounts[i]?.walletAddress);\n if (sameAccount && sameAccountsShape) {\n return state;\n }\n const updated: ConnectedWallet = {\n ...wallet,\n account: nextAccount,\n accounts: [...event.accounts],\n };\n const newPool = new Map([...state.pool, [event.connectorId, updated] as const]);\n return { ...state, pool: newPool };\n }\n\n case \"WALLET_REFRESHED\": {\n const wallet = state.pool.get(event.connectorId);\n if (!wallet) {\n return state;\n }\n const newPool = new Map([...state.pool, [event.connectorId, { ...wallet }] as const]);\n return { ...state, pool: newPool };\n }\n\n case \"ACTIVE_CHANGED\": {\n return { ...state, activeConnectorId: event.connectorId };\n }\n\n case \"SELECTION_CHANGED\": {\n const newSelection = new Map(state.selection);\n if (event.connectorId === null) {\n newSelection.delete(event.chainPlatform);\n } else {\n newSelection.set(event.chainPlatform, event.connectorId);\n }\n return { ...state, selection: newSelection };\n }\n\n case \"STATUS_RESET\": {\n return {\n ...state,\n connectingConnectorId: null,\n connectionError: null,\n connectionStatus: \"idle\",\n };\n }\n\n case \"ERROR_SET\": {\n return {\n ...state,\n connectionError: event.error,\n connectionStatus: event.error ? \"error\" : \"idle\",\n };\n }\n\n case \"RESET\": {\n return {\n ...initialState,\n isHydrated: state.isHydrated,\n isUserDisconnected: true,\n reconnectingIds: new Set(),\n };\n }\n\n default: {\n // Exhaustiveness check — TS errors if a new event type is added without a case.\n const exhaustiveCheck: never = event;\n void exhaustiveCheck;\n return state;\n }\n }\n};\n\nexport type {\n ConnectionStatus,\n ConnectionStatusEvent,\n Event,\n LifecycleEvent,\n PoolMutationEvent,\n SelectionEvent,\n State,\n};\nexport { initialState, reducer };\n","import type { StoredPoolEntry } from \"../storage/persistence\";\nimport type {\n BitcoinAdapter,\n EvmAdapter,\n PolkadotAdapter,\n SuiAdapter,\n SvmAdapter,\n WalletAdapter,\n WalletCapabilities,\n} from \"../types\";\n\n/**\n * Error thrown when a method is called on a shadow adapter — the\n * placeholder `WalletAdapter` that the store seeds into the pool when\n * an `initialState` is provided (e.g. from a server-rendered cookie\n * snapshot). Shadow adapters carry the identity and account data of a\n * previously-connected wallet, but the live wallet extension hasn't\n * been verified yet — the silent reconnect happens asynchronously\n * after mount.\n *\n * UI code that gates affordances on `wallet.connector.capabilities.*`\n * never reaches a shadow method (capabilities are all `false`). Code\n * that calls through anyway hits this typed error, which is the\n * correct loud failure: the consumer ignored the capability gate.\n *\n * Consumers wanting to wait out the reconnecting window should branch\n * on whether `connectorId` is in `state.reconnectingIds`.\n */\nclass ShadowConnectorError extends Error {\n // Stable programmatic identifier — consumers branch on `.code` to\n // distinguish this from generic connector errors. Read via\n // `toMatchObject({ code: \"BUTR_RECONNECTING\" })` in tests, which\n // static analysis can't trace.\n // fallow-ignore-next-line unused-class-member\n readonly code = \"BUTR_RECONNECTING\";\n readonly connectorId: string;\n readonly method: string;\n constructor(method: string, connectorId: string) {\n super(\n `[butr] ${method} called on shadow connector \"${connectorId}\" — wait for silent reconnect to complete (check reconnectingIds.has(id) before calling).`,\n );\n this.name = \"ShadowConnectorError\";\n this.connectorId = connectorId;\n this.method = method;\n }\n}\n\nconst ALL_FALSE_CAPABILITIES: WalletCapabilities = Object.freeze({\n getBalance: false,\n getTransactionReceipt: false,\n requestAccounts: false,\n sendTransaction: false,\n signIn: false,\n signMessage: false,\n signTransaction: false,\n subscribe: false,\n switchAccount: false,\n switchChain: false,\n});\n\n/**\n * Builds a placeholder `WalletAdapter` from a persisted pool entry.\n *\n * Used by `createWalletStore` when `WalletManagerConfig.initialState`\n * is provided: each stored entry becomes a `ConnectedWallet` whose\n * `connector` is one of these. The store flips `isHydrated` true\n * synchronously and exposes the data through the usual hooks\n * (`useActiveWallet`, `useConnectedWallets`, …) — but the connector\n * can't actually talk to a wallet yet, so its capabilities are all\n * `false` and its methods throw `ShadowConnectorError` if called.\n *\n * The hydration coordinator's silent-reconnect pass upgrades each\n * shadow to a live `WalletAdapter` by calling `createConnector(id)`\n * (which only succeeds once the live adapter has been announced via\n * discovery or registered explicitly) and replacing the pool entry.\n * On success the connector id is removed from `reconnectingIds`; on\n * failure the entry is dropped from the pool and storage.\n *\n * The entry's `name` is required (the storage validator rejects\n * entries without it); `icon` is optional only because some live\n * adapters genuinely have no icon to begin with.\n */\nconst createShadowAdapter = (entry: StoredPoolEntry): WalletAdapter => {\n const id = entry.connectorId;\n const name = entry.name;\n const icon = entry.icon;\n\n const reject = (method: string): Promise<never> =>\n Promise.reject(new ShadowConnectorError(method, id));\n\n // Shape that satisfies the intersection of `Connector<P>` and\n // `WalletBase`. Platform-specific optional methods (`signIn`,\n // `signTransaction`) are intentionally omitted — they don't exist on\n // a shadow, and their absence is a valid runtime state for the\n // per-platform adapter types (which mark them `?:`).\n const base = {\n capabilities: ALL_FALSE_CAPABILITIES,\n connect: () => reject(\"connect\"),\n disconnect: () => reject(\"disconnect\"),\n getAccount: () => reject(\"getAccount\"),\n getBalance: () => reject(\"getBalance\"),\n getSigner: () => reject(\"getSigner\"),\n getTransactionReceipt: () => reject(\"getTransactionReceipt\"),\n icon,\n id,\n name,\n sendTx: () => reject(\"sendTx\"),\n sendTxToChain: () => reject(\"sendTxToChain\"),\n signMessage: () => reject(\"signMessage\"),\n switchChain: () => reject(\"switchChain\"),\n };\n\n // Cast required: TS can't narrow the literal `chainPlatform` field through a spread.\n switch (entry.chainPlatform) {\n case \"bitcoin\": {\n return { ...base, chainPlatform: \"bitcoin\" } as BitcoinAdapter;\n }\n case \"evm\": {\n return { ...base, chainPlatform: \"evm\" } as EvmAdapter;\n }\n case \"sui\": {\n return { ...base, chainPlatform: \"sui\" } as SuiAdapter;\n }\n case \"svm\": {\n return { ...base, chainPlatform: \"svm\" } as SvmAdapter;\n }\n case \"polkadot\": {\n return { ...base, chainPlatform: \"polkadot\" } as PolkadotAdapter;\n }\n default: {\n // Exhaustive — TS errors if a ChainPlatform variant is added.\n const _exhaustive: never = entry.chainPlatform;\n void _exhaustive;\n throw new Error(`[butr] unknown chainPlatform: ${entry.chainPlatform as string}`);\n }\n }\n};\n\n/**\n * Type guard. Returns true when an adapter is a placeholder created\n * by `createShadowAdapter`. Useful for the hydration coordinator\n * (which needs to know which pool entries still need upgrading) and\n * for consumers writing wagmi-style \"is this connection verified yet\"\n * checks without subscribing to `reconnectingIds` directly.\n *\n * Detection is structural: a shadow has all capabilities set to false.\n * Live adapters always advertise at least one capability (every wallet\n * surface includes `getBalance`, `signMessage`, `switchChain` as\n * required methods, and adapter constructors set their flags\n * accordingly).\n */\nconst isShadowAdapter = (adapter: WalletAdapter): boolean => {\n const caps = adapter.capabilities;\n // Derive the check from the canonical all-false key set so a newly\n // added capability can never be silently missed: adding a flag to\n // `WalletCapabilities` forces it into `ALL_FALSE_CAPABILITIES` (the\n // type annotation enforces that), and this guard then covers it.\n return (Object.keys(ALL_FALSE_CAPABILITIES) as Array<keyof WalletCapabilities>).every(\n (key) => caps[key] === false,\n );\n};\n\nexport { createShadowAdapter, isShadowAdapter, ShadowConnectorError };\n","/** Run an async operation fire-and-forget, calling onError if it throws. */\nconst run = async (fn: () => Promise<void>, onError: (e: unknown) => void): Promise<void> => {\n try {\n await fn();\n } catch (error) {\n onError(error);\n }\n};\n\nexport { run };\n","import { createStore } from \"zustand/vanilla\";\n\nimport { logError, logWarn } from \"../logger\";\nimport type { WalletPersistence, WalletSnapshot } from \"../storage\";\nimport { WalletStorage } from \"../storage/wallet-storage\";\nimport type {\n Account,\n ChainPlatform,\n ConnectedWallet,\n WalletAdapter,\n WalletManagerConfig,\n} from \"../types\";\nimport type { ConnectionError } from \"../types/errors\";\nimport { mapConnectionError } from \"../types/errors\";\n\nimport { createConnectorLifecycle } from \"./connector-lifecycle\";\nimport { createHydrationCoordinator } from \"./hydration\";\nimport { type Event, type State, initialState, reducer } from \"./reducer\";\nimport { createShadowAdapter } from \"./shadow-adapter\";\nimport { run } from \"./wallet-store-helpers\";\n\n/**\n * Build a synchronously-populated `State` from `config.initialState`.\n * Each pool entry becomes a `ConnectedWallet` whose `connector` is a\n * shadow adapter; every connector id enters `reconnectingIds` so\n * consumers can branch on \"is this connection verified\" without\n * waiting for the async silent reconnect. `isHydrated` flips true\n * synchronously — the consumer's first render sees the persisted\n * state in the live store, not undefined.\n */\nconst seedStateFromSnapshot = (snapshot: WalletSnapshot): State => {\n const pool = new Map<string, ConnectedWallet>();\n const reconnectingIds = new Set<string>();\n for (const [connectorId, entry] of Object.entries(snapshot.pool)) {\n if (!entry) {\n continue;\n }\n const connector: WalletAdapter = createShadowAdapter(entry);\n pool.set(connectorId, {\n account: entry.account,\n accounts: [...entry.accounts],\n connector,\n });\n reconnectingIds.add(connectorId);\n }\n const selection = new Map<ChainPlatform, string>();\n for (const [platform, connectorId] of Object.entries(snapshot.selection)) {\n if (connectorId && pool.has(connectorId)) {\n selection.set(platform as ChainPlatform, connectorId);\n }\n }\n const activeConnectorId =\n snapshot.activeConnectorId && pool.has(snapshot.activeConnectorId)\n ? snapshot.activeConnectorId\n : (pool.keys().next().value ?? null);\n return {\n ...initialState,\n activeConnectorId,\n isHydrated: true,\n pool,\n reconnectingIds,\n selection,\n };\n};\n\nconst CONNECT_TIMEOUT_MS = 90_000;\nconst DEFAULT_SLOW_CONNECT_THRESHOLD_MS = 5000;\n\nconst normaliseAddress = (addr: string): string => addr.toLowerCase();\n\ntype ExtractState<S> = S extends { getState: () => infer T } ? T : never;\n\ntype RuntimeMembers = {\n _config: WalletManagerConfig;\n _storage: WalletPersistence;\n connectWallet: (\n connectorId: string,\n onSuccess?: (wallet: ConnectedWallet) => void,\n onError?: (error: Error) => void,\n ) => Promise<void>;\n disconnectWallet: (connectorId: string) => void;\n getConnectorInstance: (id: string) => ReturnType<WalletManagerConfig[\"createConnector\"]>;\n hydrateWallets: () => Promise<void>;\n refreshWallet: (connectorId: string) => void;\n requestAccounts: (connectorId: string) => Promise<void>;\n reset: () => void;\n resetConnectionStatus: () => void;\n setActiveConnector: (connectorId: string | null) => void;\n setConnectionError: (error: ConnectionError | null) => void;\n setSelection: (chainPlatform: ChainPlatform, connectorId: string | null) => void;\n setUserDisconnected: (value: boolean) => void;\n tryRestoreFromPending: (connectorId: string) => Promise<void>;\n updateWalletAccount: (connectorId: string, account: Account) => void;\n};\n\ntype WalletStore = ReturnType<typeof createWalletStore>;\ntype WalletStoreState = ExtractState<WalletStore>;\n\nconst createWalletStore = (config: WalletManagerConfig) => {\n const storageKeyPrefix = config.storageKeyPrefix || \"butr\";\n const storage = config.storage || new WalletStorage({ keyPrefix: storageKeyPrefix });\n\n // Storage-error handler. Default: `console.warn` (preserves the\n // pre-`onStorageError` behaviour). Consumer-provided callback routes\n // failures through their telemetry pipeline.\n const reportStorageError = (context: string) => (error: unknown) => {\n if (config.onStorageError) {\n try {\n config.onStorageError(error, context);\n } catch (cbError: unknown) {\n logWarn(\"[butr] onStorageError threw:\", cbError);\n }\n return;\n }\n logWarn(`[butr] ${context}:`, error);\n };\n\n // Owns the full restore lifecycle: read storage, instantiate adapters,\n // restore in parallel, park entries whose adapter wasn't registered\n // yet, drain parked entries when discovery announces a matching id.\n // `pendingRestores` lives inside the coordinator — the runtime no\n // longer manages the queue directly.\n const hydration = createHydrationCoordinator(storage, config.createConnector);\n\n return createStore<State & RuntimeMembers>()((set, get) => {\n const dispatch = (event: Event) => {\n set((prev) => reducer(prev, event), false);\n };\n\n // Returns the write Promise so connect/disconnect can await durability;\n // `WalletStorage` serializes pool mutations internally so fire-and-forget callers are safe.\n const persistPool = (): Promise<void> =>\n run(() => storage.setPool(get().pool), reportStorageError(\"failed to persist pool\"));\n\n const persistSelection = (): Promise<void> =>\n run(\n () => storage.setSelection(get().selection),\n reportStorageError(\"failed to persist selection\"),\n );\n\n const persistActive = (): Promise<void> =>\n run(\n () => storage.setActiveConnectorId(get().activeConnectorId),\n reportStorageError(\"failed to persist active connector\"),\n );\n\n // Single entry point for \"the pool entry's exposed accounts\n // changed.\" Three call sites use it: the wallet-event bridge\n // (`accountChanged`), the consumer-facing `updateWalletAccount`\n // action, and the `requestAccounts` action. `active` is set when\n // the caller knows which address is now active (wallet event,\n // manual update); omitted when the caller just refreshed the\n // list and wants the reducer's preserve-or-fallback logic.\n const refreshPoolEntry = (connectorId: string, accounts: Array<Account>, active?: Account) => {\n dispatch({ accounts, active, connectorId, type: \"ACCOUNTS_REFRESHED\" });\n void persistPool();\n };\n\n // Owns the \"exactly one subscription per connector\" invariant,\n // the event-to-handler choreography, and the unsubscribers Map.\n // Attach is idempotent: the runtime calls it after every\n // restore / connect without first checking whether a prior\n // subscription exists.\n const lifecycle = createConnectorLifecycle({\n onAccountChanged: (connectorId, accounts, active) => {\n // Full-replace so the pool mirrors the wallet's current exposure; the wallet picks `active`.\n refreshPoolEntry(connectorId, [...accounts], active);\n },\n onDisconnected: (connectorId, chainPlatform) => {\n // Mirror an external disconnect into the reducer so the UI\n // hides the wallet, but DON'T touch storage — EIP-1193 emits\n // `accountsChanged: []` (which we forward as a `disconnected`\n // event) both when the user revokes permissions AND when\n // MetaMask simply auto-locks. The two are indistinguishable\n // from our side, so persisting the empty pool would erase the\n // saved connection on every wallet lock. Keeping storage\n // intact lets the next hydrate retry — the user-locked case\n // self-heals once they unlock and reload, and a genuine\n // revocation gets cleaned up by the next call to\n // `disconnectWallet` (or just lingers as dead bytes).\n dispatch({ connectorId, type: \"DISCONNECTED\" });\n config.onDisconnect?.(chainPlatform);\n },\n });\n\n const seeded: State = config.initialState\n ? seedStateFromSnapshot(config.initialState)\n : initialState;\n\n return {\n ...seeded,\n _config: config,\n _storage: storage,\n connectWallet: async (connectorId, onSuccess, onError) => {\n get().setUserDisconnected(false);\n\n const connector = config.createConnector(connectorId);\n if (!connector) {\n throw new Error(`Failed to create connector for ${connectorId}`);\n }\n\n dispatch({ connectorId, type: \"CONNECT_STARTED\" });\n\n // Slow-connect telemetry. Fires once if the wallet doesn't\n // resolve within the configured threshold. Cleared in finally.\n const slowThreshold = config.slowConnectThresholdMs ?? DEFAULT_SLOW_CONNECT_THRESHOLD_MS;\n const slowTimer = config.onSlowConnect\n ? setTimeout(() => {\n try {\n config.onSlowConnect?.(connectorId);\n } catch (cbError: unknown) {\n logWarn(\"[butr] onSlowConnect threw:\", cbError);\n }\n }, slowThreshold)\n : null;\n\n // Hoisted so `finally` can clear the connect-timeout timer —\n // otherwise the timer and its reject closure outlive every\n // settled connect by the full CONNECT_TIMEOUT_MS.\n let connectTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n try {\n const connectPromise = connector.connect();\n // oxlint-disable-next-line promise/prefer-await-to-then -- suppress unhandled rejection; we await via Promise.race below\n void connectPromise.catch(() => {});\n await Promise.race([\n connectPromise,\n new Promise((_, reject) => {\n connectTimeoutId = setTimeout(() => {\n reject(new Error(\"Connection timeout\"));\n }, CONNECT_TIMEOUT_MS);\n }),\n ]);\n\n const account = await connector.getAccount();\n if (!account) {\n throw new Error(\"Failed to get account\");\n }\n\n // Pull all known accounts when the connector supports it.\n const fetchedAccounts = connector.getAccounts\n ? await connector.getAccounts().catch(() => null)\n : null;\n const accounts =\n fetchedAccounts && fetchedAccounts.length > 0 ? fetchedAccounts : [account];\n\n const entry: ConnectedWallet = { account, accounts, connector };\n dispatch({ connectorId, entry, type: \"CONNECT_SUCCEEDED\" });\n\n lifecycle.attach(connectorId, connector);\n\n // Await so callers can `await connectWallet(id)` and trust\n // that storage reflects the new connection on the very next\n // line — load `useConnectedWallets` snapshots, expect\n // localStorage to contain the entry, etc.\n await Promise.all([persistPool(), persistSelection(), persistActive()]);\n\n config.onConnect?.(entry);\n onSuccess?.(entry);\n } catch (error) {\n const normalised = mapConnectionError(error);\n dispatch({ error: normalised, type: \"CONNECT_FAILED\" });\n try {\n await connector.disconnect?.();\n } catch (disconnectError: unknown) {\n logWarn(\"[butr] disconnect during error recovery failed:\", disconnectError);\n }\n try {\n config.onConnectError?.(normalised, connectorId);\n } catch (cbError: unknown) {\n logWarn(\"[butr] onConnectError threw:\", cbError);\n }\n onError?.(error as Error);\n throw error;\n } finally {\n if (connectTimeoutId) {\n clearTimeout(connectTimeoutId);\n }\n if (slowTimer) {\n clearTimeout(slowTimer);\n }\n }\n },\n\n disconnectWallet: (connectorId) => {\n get().setUserDisconnected(true);\n\n const state = get();\n if (!state.isHydrated) {\n return;\n }\n const wallet = state.pool.get(connectorId);\n if (!wallet) {\n return;\n }\n\n lifecycle.detach(connectorId);\n\n void run(() => wallet.connector.disconnect?.() ?? Promise.resolve(), logError);\n\n const platform = wallet.connector.chainPlatform;\n dispatch({ connectorId, type: \"DISCONNECTED\" });\n\n if (get().pool.size === 0) {\n void run(() => storage.clearAll(), reportStorageError(\"failed to clear storage\"));\n } else {\n // Explicit eviction so storage doesn't keep retrying the\n // disconnected wallet on the next load. `persistPool` is\n // additive (see `WalletStorage.setPool`), so we can't rely\n // on it to remove entries — that's what `removePoolEntry`\n // is for.\n void run(\n () => storage.removePoolEntry(connectorId),\n reportStorageError(\"failed to remove pool entry\"),\n );\n void persistSelection();\n void persistActive();\n }\n\n config.onDisconnect?.(platform);\n },\n\n getConnectorInstance: (id) => config.createConnector(id),\n\n hydrateWallets: async () => {\n const result = await hydration.hydrate();\n dispatch({\n activeConnectorId: result.activeConnectorId,\n isUserDisconnected: result.isUserDisconnected,\n pool: result.pool,\n selection: result.selection,\n type: \"HYDRATED\",\n });\n // Wire up wallet-side event subscriptions for every restored\n // connector so account/chain swaps after a refresh keep the\n // reducer in sync without consumer effort.\n for (const [connectorId, wallet] of result.pool) {\n lifecycle.attach(connectorId, wallet.connector);\n }\n // Persist any reconciled values back so future loads stay consistent.\n await Promise.all([persistSelection(), persistActive()]);\n // Drain: catch the race where a Wallet Standard adapter\n // announced BEFORE hydration finished populating its queue.\n // Without this, the discovery callback's\n // `tryRestoreFromPending(adapter.id)` would have hit the\n // empty queue and silently returned, leaving SVM wallets\n // un-restored on reload. The coordinator's `pendingIds()`\n // is the post-hydrate snapshot; each id resolves\n // independently. Late-restore failures surface per-entry\n // inside `tryRestoreFromPending`.\n // Each restore is fire-and-forget with its own handler: one\n // rejecting restore (e.g. a throwing `createConnector`) must\n // not become an unhandled rejection, but it must still log —\n // swallowing it would hide genuine restore failures.\n for (const id of hydration.pendingIds()) {\n void run(\n () => get().tryRestoreFromPending(id),\n (e) => logWarn(`[butr] late restore rejected for ${id}:`, e),\n );\n }\n // Surface the hydration outcome. Three buckets: restored,\n // pending (waiting for adapter announcement), dropped\n // (genuine restore failures). The default `console.warn`\n // for dropped entries is replaced by this callback when\n // set — consumers route to telemetry / UX hints.\n if (config.onHydrated) {\n try {\n config.onHydrated({\n dropped: result.dropped,\n pendingIds: [...result.pendingIds],\n restoredIds: [...result.pool.keys()],\n });\n } catch (cbError: unknown) {\n logWarn(\"[butr] onHydrated threw:\", cbError);\n }\n } else if (result.dropped.length > 0) {\n // Preserve the pre-`onHydrated` console.warn behaviour\n // when no callback is set, so silent drops still log.\n for (const { connectorId, reason } of result.dropped) {\n logWarn(`[butr] failed to restore connector ${connectorId}:`, reason);\n }\n }\n },\n refreshWallet: (connectorId) => {\n dispatch({ connectorId, type: \"WALLET_REFRESHED\" });\n },\n\n requestAccounts: async (connectorId) => {\n const entry = get().pool.get(connectorId);\n if (!entry) {\n return;\n }\n // Ask the wallet to open its picker (if supported). EVM\n // wallets honour this via `wallet_requestPermissions`;\n // Wallet Standard wallets typically have no equivalent\n // RPC, so the call resolves immediately and the refresh\n // below simply re-reads the current list.\n await entry.connector.requestAccounts?.();\n const fresh = entry.connector.getAccounts\n ? await entry.connector.getAccounts().catch(() => null)\n : null;\n if (!fresh || fresh.length === 0) {\n return;\n }\n // No `active` — the reducer preserves the current active\n // if it's still in the refreshed list, else picks [0].\n refreshPoolEntry(connectorId, fresh);\n },\n\n reset: () => {\n get().setUserDisconnected(true);\n\n const state = get();\n if (!state.isHydrated) {\n return;\n }\n\n lifecycle.detachAll();\n\n for (const wallet of state.pool.values()) {\n void run(() => wallet.connector.disconnect?.() ?? Promise.resolve(), logError);\n }\n\n void run(() => storage.clearAll(), reportStorageError(\"failed to clear storage\"));\n\n if (config.onReset) {\n const onReset = config.onReset;\n void run(() => Promise.resolve(onReset()), logError);\n }\n\n dispatch({ type: \"RESET\" });\n },\n\n resetConnectionStatus: () => {\n dispatch({ type: \"STATUS_RESET\" });\n },\n\n setActiveConnector: (connectorId) => {\n dispatch({ connectorId, type: \"ACTIVE_CHANGED\" });\n void persistActive();\n },\n\n setConnectionError: (error) => {\n dispatch({ error, type: \"ERROR_SET\" });\n },\n\n setSelection: (chainPlatform, connectorId) => {\n dispatch({ chainPlatform, connectorId, type: \"SELECTION_CHANGED\" });\n void persistSelection();\n },\n\n setUserDisconnected: (value: boolean) => {\n dispatch({ type: \"USER_DISCONNECTED_SET\", value });\n void run(\n () => storage.markUserDisconnected(value),\n reportStorageError(\"failed to persist disconnect intent\"),\n );\n },\n\n tryRestoreFromPending: async (connectorId) => {\n // Note: deliberately NOT gating on `isUserDisconnected`.\n // The eager hydration path doesn't check that flag either —\n // stored entries restore on reload regardless of whether\n // the user's most recent action was a disconnect. The\n // late-restore path mirrors that policy for symmetry.\n const outcome = await hydration.drainPending(connectorId);\n if (!outcome) {\n return;\n }\n if (outcome.kind === \"fail\") {\n logWarn(`[butr] late restore failed for ${connectorId}:`, outcome.error);\n return;\n }\n // Reuse the reducer's connect-success path so selection /\n // active reconciliation matches a normal connect flow.\n dispatch({ connectorId, entry: outcome.entry, type: \"CONNECT_SUCCEEDED\" });\n lifecycle.attach(connectorId, outcome.entry.connector);\n await Promise.all([persistPool(), persistSelection(), persistActive()]);\n config.onConnect?.(outcome.entry);\n },\n\n updateWalletAccount: (connectorId, account) => {\n // Routes through ACCOUNTS_REFRESHED so the manual and wallet-event paths share a reducer case.\n const entry = get().pool.get(connectorId);\n if (!entry) {\n return;\n }\n const newChain = account.chain;\n const remapped = entry.accounts.map((a) =>\n a.chain.id === newChain.id\n ? a\n : {\n chain: newChain,\n id: `${newChain.id}:${normaliseAddress(a.walletAddress)}`,\n walletAddress: a.walletAddress,\n },\n );\n const seen = remapped.some(\n (a) => normaliseAddress(a.walletAddress) === normaliseAddress(account.walletAddress),\n );\n const accounts = seen ? remapped : [...remapped, account];\n refreshPoolEntry(connectorId, accounts, account);\n },\n };\n });\n};\n\nexport type { WalletStore, WalletStoreState };\nexport { createWalletStore };\n","import type { StorageDriver } from \"./persistence\";\n\ntype InitialCookies = Iterable<[string, string]> | Readonly<Record<string, string>>;\n\ntype CookieDriverOptions = {\n /**\n * Cookie `domain` attribute. Omit to scope to the current host.\n * Set to a parent domain (e.g. `.example.com`) to share state\n * across subdomains.\n */\n domain?: string;\n /**\n * Snapshot of cookies for the SSR pass — typically the result of\n * Next.js' `cookies()` (from `next/headers`) or a parsed\n * `req.headers.cookie`. Used only when `document` is unavailable.\n *\n * When provided, `getItem` reads from this snapshot during the\n * server render so the store sees the same persisted state the\n * client will see after hydration. Writes remain no-ops on the\n * server — emitting `Set-Cookie` has to be done by the framework\n * layer that owns the response.\n */\n initialCookies?: InitialCookies;\n /**\n * Lifetime in seconds. Defaults to 30 days. Pass `undefined`\n * (the default) for \"until the session ends\" — but note that\n * butr persists wallet state across sessions, so a finite\n * max-age is usually what consumers want.\n */\n maxAgeSeconds?: number;\n /**\n * URL path the cookie applies to. Defaults to `/` (whole origin).\n */\n path?: string;\n /**\n * `SameSite` attribute. Defaults to `\"lax\"` — restrictive enough\n * to avoid CSRF on cross-origin POSTs, permissive enough for\n * top-level navigations.\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n /**\n * `Secure` attribute. Defaults to `true` (cookies only sent over\n * HTTPS). Force `false` for local development on plain `http://`.\n */\n secure?: boolean;\n};\n\nconst DEFAULT_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;\n\nconst encode = (value: string): string => encodeURIComponent(value);\nconst decode = (value: string): string => decodeURIComponent(value);\n\nconst readCookies = (): Map<string, string> => {\n const out = new Map<string, string>();\n if (typeof document === \"undefined\") {\n return out;\n }\n const cookieString = document.cookie;\n if (!cookieString) {\n return out;\n }\n for (const segment of cookieString.split(\";\")) {\n const trimmed = segment.trim();\n if (!trimmed) {\n continue;\n }\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const name = trimmed.slice(0, eq);\n const raw = trimmed.slice(eq + 1);\n try {\n out.set(name, decode(raw));\n } catch {\n // Malformed entry; skip rather than crash hydration.\n }\n }\n return out;\n};\n\nconst buildCookieString = (\n name: string,\n value: string,\n options: CookieDriverOptions,\n expired = false,\n): string => {\n const parts: Array<string> = [`${name}=${encode(value)}`, `Path=${options.path ?? \"/\"}`];\n if (options.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n if (expired) {\n parts.push(\"Max-Age=0\");\n } else {\n const maxAge = options.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;\n parts.push(`Max-Age=${maxAge}`);\n }\n parts.push(`SameSite=${options.sameSite ?? \"lax\"}`);\n if (options.secure ?? true) {\n parts.push(\"Secure\");\n }\n return parts.join(\"; \");\n};\n\nconst toCookieMap = (input: InitialCookies | undefined): Map<string, string> | null => {\n if (!input) {\n return null;\n }\n if (typeof (input as Iterable<[string, string]>)[Symbol.iterator] === \"function\") {\n return new Map(input as Iterable<[string, string]>);\n }\n return new Map(Object.entries(input as Readonly<Record<string, string>>));\n};\n\n/**\n * Cookie-backed storage driver. Reads/writes `document.cookie` —\n * server-readable, survives reloads, scoped per `domain`/`path`.\n *\n * **When to use this:** SSR apps that need to know who's connected\n * during the server render (so they can stream the connected-wallet\n * UI without a client-side hydration flicker). Pass `initialCookies`\n * from a server-side cookie source (e.g. `cookies()` in Next.js'\n * `next/headers`, or a parsed `req.headers.cookie`) and the same\n * driver will serve those values during the server render and switch\n * to `document.cookie` once it mounts in the browser.\n *\n * **Trade-offs vs `localStorage`:** cookies travel with every\n * request, so they cost bytes on the wire. Keep the storage key\n * prefix short, and prefer this driver for the `persistent` slot\n * only — the `session` slot can stay in `sessionStorage` (which\n * cookies can't natively model anyway).\n *\n * **Server-side writes are no-ops.** Emitting `Set-Cookie` requires\n * access to the framework's response object, which a storage driver\n * shouldn't reach into. The store doesn't mutate persisted state\n * during the SSR pass anyway — writes only fire after client mount,\n * once `document.cookie` is reachable.\n */\nconst createCookieStorageDriver = (options: CookieDriverOptions = {}): StorageDriver => {\n const seeded = toCookieMap(options.initialCookies);\n\n if (typeof document === \"undefined\") {\n if (!seeded) {\n return {\n getItem() {\n return null;\n },\n removeItem() {\n // server-side no-op\n },\n setItem() {\n // server-side no-op\n },\n };\n }\n return {\n getItem(key) {\n return seeded.get(key) ?? null;\n },\n removeItem() {\n // server-side no-op — framework owns Set-Cookie\n },\n setItem() {\n // server-side no-op — framework owns Set-Cookie\n },\n };\n }\n return {\n getItem(key) {\n return readCookies().get(key) ?? null;\n },\n removeItem(key) {\n // eslint-disable-next-line unicorn/no-document-cookie -- cookie storage driver is the document.cookie abstraction by design\n document.cookie = buildCookieString(key, \"\", options, true);\n },\n setItem(key, value) {\n // eslint-disable-next-line unicorn/no-document-cookie -- cookie storage driver is the document.cookie abstraction by design\n document.cookie = buildCookieString(key, value, options);\n },\n };\n};\n\nexport type { CookieDriverOptions, InitialCookies };\nexport { createCookieStorageDriver };\n","import { logWarn } from \"../logger\";\nimport { CHAIN_PLATFORMS } from \"../types\";\nimport type { ChainPlatform } from \"../types\";\n\nimport type { StoredPoolEntry, StoredPoolRecord, StoredSelectionRecord } from \"./persistence\";\n\nconst VALID_CHAIN_PLATFORMS = new Set<ChainPlatform>(CHAIN_PLATFORMS);\n\n/**\n * Server-safe view of a butr-persisted session — everything you can\n * know about a user's connected wallets from the cookie payload alone,\n * without instantiating a `Connector`.\n *\n * Notably absent: the `Connector` instance. A wallet extension exists\n * only in the browser, so a server render can know *which* wallet was\n * connected and *what address* it held, but cannot dispatch\n * `signMessage`/`sendTransaction` on it. Splitting display from action\n * along this seam keeps the impossibility expressed in the types\n * rather than hidden inside a runtime check.\n */\ntype WalletSnapshot = {\n activeConnectorId: string | null;\n pool: StoredPoolRecord;\n selection: StoredSelectionRecord;\n};\n\ntype CookieSource =\n | Iterable<{ name: string; value: string }>\n | Iterable<[string, string]>\n | Readonly<Record<string, string>>;\n\ntype SnapshotOptions = {\n /**\n * Same prefix passed to `WalletManagerProvider` / `WalletStorage`.\n * Defaults to `\"butr\"` to match the library default.\n */\n keyPrefix?: string;\n};\n\nconst EMPTY_SNAPSHOT: WalletSnapshot = Object.freeze({\n activeConnectorId: null,\n pool: Object.freeze({}) as StoredPoolRecord,\n selection: Object.freeze({}) as StoredSelectionRecord,\n});\n\nconst toCookieMap = (input: CookieSource): Map<string, string> => {\n // Plain record: `{ name: \"value\", ... }`. Distinguished from\n // iterables by the absence of a `Symbol.iterator` callable.\n const maybeIterator = (input as { [Symbol.iterator]?: unknown })[Symbol.iterator];\n if (typeof maybeIterator !== \"function\") {\n return new Map(Object.entries(input as Readonly<Record<string, string>>));\n }\n const out = new Map<string, string>();\n for (const entry of input as Iterable<{ name: string; value: string } | [string, string]>) {\n if (Array.isArray(entry)) {\n const [name, value] = entry;\n if (typeof name === \"string\" && typeof value === \"string\") {\n out.set(name, value);\n }\n continue;\n }\n if (\n entry &&\n typeof entry === \"object\" &&\n \"name\" in entry &&\n \"value\" in entry &&\n typeof entry.name === \"string\" &&\n typeof entry.value === \"string\"\n ) {\n out.set(entry.name, entry.value);\n }\n }\n return out;\n};\n\nconst isValidAccount = (value: unknown): boolean => {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const account = value as Record<string, unknown>;\n if (typeof account.walletAddress !== \"string\" || typeof account.id !== \"string\") {\n return false;\n }\n if (!account.chain || typeof account.chain !== \"object\") {\n return false;\n }\n return true;\n};\n\nconst isValidPoolEntry = (key: string, value: unknown): value is StoredPoolEntry => {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const entry = value as Record<string, unknown>;\n if (typeof entry.connectorId !== \"string\" || entry.connectorId !== key) {\n return false;\n }\n if (typeof entry.chainPlatform !== \"string\") {\n return false;\n }\n if (!VALID_CHAIN_PLATFORMS.has(entry.chainPlatform as ChainPlatform)) {\n return false;\n }\n if (typeof entry.name !== \"string\" || entry.name.length === 0) {\n return false;\n }\n if (entry.icon !== undefined && typeof entry.icon !== \"string\") {\n return false;\n }\n if (!isValidAccount(entry.account)) {\n return false;\n }\n if (!Array.isArray(entry.accounts) || !entry.accounts.every(isValidAccount)) {\n return false;\n }\n return true;\n};\n\nconst parsePool = (raw: string | undefined): StoredPoolRecord => {\n if (!raw) {\n return {};\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n return {};\n }\n const result: StoredPoolRecord = {};\n for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {\n if (isValidPoolEntry(key, value)) {\n result[key] = value;\n } else {\n logWarn(`[butr] readWalletSnapshot: dropping invalid pool entry for ${key}`);\n }\n }\n return result;\n } catch (error) {\n logWarn(\"[butr] readWalletSnapshot: failed to parse pool cookie:\", error);\n return {};\n }\n};\n\nconst parseSelection = (raw: string | undefined): StoredSelectionRecord => {\n if (!raw) {\n return {};\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\") {\n return {};\n }\n const result: StoredSelectionRecord = {};\n for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {\n if (\n VALID_CHAIN_PLATFORMS.has(key as ChainPlatform) &&\n typeof value === \"string\" &&\n value.length > 0\n ) {\n result[key as ChainPlatform] = value;\n }\n }\n return result;\n } catch (error) {\n logWarn(\"[butr] readWalletSnapshot: failed to parse selection cookie:\", error);\n return {};\n }\n};\n\n/**\n * Parse a cookie source into a server-safe `WalletSnapshot`.\n *\n * Pure, sync, no `document`, no React — runnable in any environment\n * (Server Component, route handler, edge middleware, even client\n * code). Pair with `createCookieStorageDriver({ initialCookies })`\n * and `<WalletManagerProvider initialSnapshot={…} />` to render a\n * connected shell server-side without a hydration flash.\n *\n * **Stale-snapshot semantics.** The snapshot reflects whatever the\n * browser most recently persisted. If the user has since uninstalled\n * the wallet, switched accounts, or disconnected in another tab, the\n * client-side hydration will reconcile reality and the live store\n * will diverge from the snapshot. Treat the snapshot as an\n * *optimistic* shell — accurate enough to avoid a paint flicker,\n * authoritative only after `useIsHydrated()` is true.\n *\n * **Inputs.** Accepts the three shapes Next.js / Express / Hono /\n * generic-Node cookie code naturally produces:\n * - A plain object: `{ \"butr-pool\": \"{...}\", … }`\n * - An array of `{ name, value }` (Next.js' `cookies().getAll()`)\n * - An iterable of `[name, value]` tuples\n *\n * Malformed entries are dropped with a `logWarn` (same policy as\n * `WalletStorage.getPool`) — a cross-tab corruption shouldn't crash\n * the server render.\n */\nconst readWalletSnapshot = (\n source: CookieSource,\n options: SnapshotOptions = {},\n): WalletSnapshot => {\n const keyPrefix = options.keyPrefix || \"butr\";\n const cookies = toCookieMap(source);\n\n const pool = parsePool(cookies.get(`${keyPrefix}-pool`));\n const selection = parseSelection(cookies.get(`${keyPrefix}-selection`));\n\n const rawActive = cookies.get(`${keyPrefix}-active`);\n let activeConnectorId: string | null = null;\n if (rawActive && rawActive.length > 0 && pool[rawActive]) {\n activeConnectorId = rawActive;\n } else {\n // Mirror `HydrationCoordinator.hydrate` selection-fallback: when no\n // explicit active is stored, surface any pool member so the render\n // shell can still show \"connected\" instead of \"disconnected\".\n const firstKey = Object.keys(pool)[0];\n if (firstKey) {\n activeConnectorId = firstKey;\n }\n }\n\n return { activeConnectorId, pool, selection };\n};\n\nexport type { CookieSource, SnapshotOptions, WalletSnapshot };\nexport { EMPTY_SNAPSHOT, readWalletSnapshot };\n","import type { ConnectedWallet } from \"./types\";\n\n/**\n * Two wallet snapshots are equivalent for selector purposes iff they\n * share connectorId, active account address, and active account chain\n * id. Used by `useStoreWithEqualityFn` consumers (active-wallet,\n * selected-wallet, useWalletEntry) to suppress spurious re-renders\n * when the underlying Map churns but the resolved entry hasn't changed.\n *\n * Hoisted to its own module so the equivalence rule lives in one place\n * — if we ever extend the snapshot (e.g. to consider `accounts.length`),\n * every selector hook picks up the new rule for free.\n */\nconst walletEqual = (a: ConnectedWallet | undefined, b: ConnectedWallet | undefined): boolean => {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n return (\n a.connector.id === b.connector.id &&\n a.account.walletAddress === b.account.walletAddress &&\n a.account.chain.id === b.account.chain.id\n );\n};\n\nexport { walletEqual };\n","/**\n * Normalize a wallet-announced icon string.\n *\n * Wallets announce their icon through external metadata — EIP-6963\n * `providerInfo.icon`, Wallet Standard `wallet.icon`. That value is\n * not under butr's control, and some wallets ship data-URI icons with\n * surrounding whitespace (a newline left over from a pretty-printed\n * manifest). Strict consumers reject it: Next.js's `<Image>` throws\n * because `src` must not start with a control character.\n *\n * Trims surrounding whitespace and treats an all-whitespace (or empty)\n * icon as absent, so consumers get either a usable string or\n * `undefined` — never a blank or malformed one. `undefined` passes\n * through untouched.\n */\nconst sanitizeIcon = (icon: string | undefined): string | undefined => {\n if (icon === undefined) {\n return undefined;\n }\n const trimmed = icon.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n};\n\nexport { sanitizeIcon };\n","/**\n * Shared byte-encoding helpers for the connector packages.\n *\n * These functions sit directly on the signing/address path of every\n * chain. They used to be hand-reimplemented in ~10 connector files; a\n * single tested module removes the drift surface (a `padStart` omission\n * or base64 variant mismatch corrupts signatures/addresses for one chain\n * only, and the divergence is invisible because the copies look \"the\n * same\").\n *\n * Hex prefixing diverges across chains, so the module exposes **explicit\n * variants** rather than one function:\n * - {@link bytesToHex} returns bare hex (Bitcoin, Ledger).\n * - {@link bytesToHexPrefixed} returns `0x`-prefixed hex (EVM, Polkadot).\n * - {@link hexToBytes} tolerantly strips an optional `0x` (all callers).\n */\n\n/** Bare lowercase hex — no `0x` prefix (Bitcoin, Ledger). */\nconst bytesToHex = (bytes: Uint8Array): string => {\n let hex = \"\";\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, \"0\");\n }\n return hex;\n};\n\n/** `0x`-prefixed lowercase hex (EVM, Polkadot). */\nconst bytesToHexPrefixed = (bytes: Uint8Array): string => `0x${bytesToHex(bytes)}`;\n\n/**\n * Decode hex (with or without a leading `0x`) into raw bytes. Throws on\n * odd-length input or non-hex characters rather than silently producing\n * `NaN`-filled bytes.\n */\nconst hexToBytes = (hex: string): Uint8Array => {\n const clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n if (clean.length % 2 !== 0) {\n throw new TypeError(\"Invalid hex: odd length\");\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i += 1) {\n const byte = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(byte)) {\n throw new TypeError(`Invalid hex character at offset ${i * 2}`);\n }\n out[i] = byte;\n }\n return out;\n};\n\n/**\n * Cross-platform base64 → `Uint8Array`. `atob` is available everywhere\n * butr runs (browsers, RN since Hermes, Node 16+, Bun, Deno).\n */\nconst base64ToBytes = (b64: string): Uint8Array => {\n const binary = atob(b64);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n out[i] = binary.codePointAt(i) ?? 0;\n }\n return out;\n};\n\n/** Cross-platform `Uint8Array` → base64. */\nconst bytesToBase64 = (bytes: Uint8Array): string => {\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCodePoint(byte);\n }\n return btoa(binary);\n};\n\nexport { base64ToBytes, bytesToBase64, bytesToHex, bytesToHexPrefixed, hexToBytes };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,yBAAyB,aAA0D;CACvF,SAAS,QAAQ,WAAW,CAAC;CAC7B,KAAK,QAAQ,OAAO,CAAC;CACrB,UAAU,QAAQ,YAAY,CAAC;CAC/B,KAAK,QAAQ,OAAO,CAAC;CACrB,KAAK,QAAQ,OAAO,CAAC;AACvB;;;;;;;;;;;;;;;;;ACXA,MAAM,sBAAsB,QAAkC;CAC5D,IAAI,eAAe,OAAO;EACxB,MAAM,UAAU,IAAI;EACpB,MAAM,QAAQ,QAAQ,YAAY;EAElC,IAAI,YAAY,sBACd,OAAO;GAAE,MAAM;GAAW;EAAQ;EAEpC,IAAI,YAAY,2BAA2B,MAAM,SAAS,eAAe,GACvE,OAAO;GAAE,MAAM;GAAgB;EAAQ;EAGzC,MAAM,OAAQ,IAA2B;EACzC,IAAI,SAAS,MACX,OAAO;GAAE,MAAM;GAAgB;EAAQ;EAEzC,IAAI,SAAS,QACX,OAAO;GAAE,MAAM;GAAkB;EAAQ;EAK3C,IAAI,SAAS,QAAQ,SAAS,QAAQ,SAAS,MAC7C,OAAO;GAAE,MAAM;GAAgB;EAAQ;EAGzC,IAAI,MAAM,SAAS,eAAe,KAAK,MAAM,SAAS,aAAa,GACjE,OAAO;GAAE,MAAM;GAAgB;EAAQ;EAEzC,IAAI,MAAM,SAAS,QAAQ,GACzB,OAAO;GAAE,MAAM;GAAgB;EAAQ;EAEzC,IAAI,MAAM,SAAS,OAAO,MAAM,MAAM,SAAS,UAAU,KAAK,MAAM,SAAS,aAAa,IACxF,OAAO;GAAE,MAAM;GAAiB;EAAQ;EAG1C,OAAO;GAAE,OAAO;GA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UAA8B;CACnD,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OACjB,UAAU,OAAO,cAAc,IAAI;CAErC,OAAO,KAAK,MAAM;AACpB"}
1
+ {"version":3,"file":"index.js","names":["VALID_CHAIN_PLATFORMS","isChainPlatform","toCookieMap"],"sources":["../src/types/chains-by-platform.ts","../src/types/errors.ts","../src/types/wallet.ts","../src/wallet-source.ts","../src/store/shadow-adapter.ts","../src/logger.ts","../src/storage/browser-storage-driver.ts","../src/storage/validation.ts","../src/storage/wallet-storage.ts","../src/store/connector-lifecycle.ts","../src/store/hydration.ts","../src/store/reducer.ts","../src/store/wallet-store-helpers.ts","../src/store/wallet-store.ts","../src/storage/cookie-storage-driver.ts","../src/storage/snapshot.ts","../src/wallet-equal.ts","../src/sanitize-icon.ts","../src/encoding/bytes.ts"],"sourcesContent":["import type { ChainBase } from \"./chain\";\nimport type { ChainPlatform } from \"./wallet\";\n\n/**\n * Map of every chain platform to the list of chains the consumer wants\n * to expose to its UI (chain switcher, picker, etc).\n *\n * The platform key set is fixed by `ChainPlatform`. The value is the\n * chain list; empty when the consumer doesn't want to support that\n * platform's chains in this view. This is the only type that callers\n * write down; the values come from per-platform packages\n * (`EVM_CHAINS_LIST`, `SVM_CHAINS_LIST`, etc).\n */\ntype ChainsByPlatform = Readonly<Record<ChainPlatform, ReadonlyArray<ChainBase>>>;\n\n/**\n * Build a fully-populated `ChainsByPlatform` from a partial. Platforms\n * the consumer doesn't specify default to an empty list.\n *\n * Use this in apps that target one or two chain platforms; importing\n * only those packages keeps unused chain registries out of the bundle.\n * Apps that want every chain reach for `CHAINS_BY_PLATFORM` from\n * `@usebutr/wallets` instead.\n *\n * @example\n * // EVM-only app: Solana/Sui/Bitcoin tables never enter the bundle\n * import { EVM_CHAINS_LIST } from \"@usebutr/evm\";\n * import { buildChainsByPlatform } from \"@usebutr/core\";\n *\n * const chains = buildChainsByPlatform({ evm: EVM_CHAINS_LIST });\n *\n * @example\n * // Multi-chain app: pull from each package the app actually uses\n * import { EVM_CHAINS_LIST } from \"@usebutr/evm\";\n * import { SVM_CHAINS_LIST } from \"@usebutr/svm\";\n *\n * const chains = buildChainsByPlatform({\n * evm: EVM_CHAINS_LIST,\n * svm: SVM_CHAINS_LIST,\n * });\n */\nconst buildChainsByPlatform = (partial: Partial<ChainsByPlatform>): ChainsByPlatform => ({\n bitcoin: partial.bitcoin ?? [],\n evm: partial.evm ?? [],\n polkadot: partial.polkadot ?? [],\n sui: partial.sui ?? [],\n svm: partial.svm ?? [],\n});\n\nexport type { ChainsByPlatform };\nexport { buildChainsByPlatform };\n","/**\n * Tagged union of normalised connection errors.\n *\n * butr maps thrown values from connectors (which vary across wallet SDKs:\n * MetaMask uses EIP-1193 codes, Phantom throws stringly-typed errors,\n * embedded SDKs throw their own classes) into a small set of UX-meaningful\n * variants. Consumers branch on `kind` instead of regexing message strings.\n *\n * `message` is always present and human-readable. `cause` preserves the\n * original thrown value so callers can inspect raw connector errors when\n * the variant is `Unknown`.\n */\ntype ConnectionError =\n | { kind: \"UserRejected\"; message: string }\n | { kind: \"RequestPending\"; message: string }\n | { kind: \"WalletLocked\"; message: string }\n | { actualChain?: string; expectedChain?: string; kind: \"ChainMismatch\"; message: string }\n | { kind: \"NotConnected\"; message: string }\n | { kind: \"Timeout\"; message: string }\n | { cause?: unknown; kind: \"Unknown\"; message: string };\n\ntype ConnectionErrorKind = ConnectionError[\"kind\"];\n\n/**\n * Normalise a thrown value into a `ConnectionError`.\n *\n * Recognises:\n * - butr's own `Error(\"Connection timeout\")` (from the 90s connect timeout)\n * - butr's own `Error(\"Failed to get account\")` (from the connect flow)\n * - EIP-1193 numeric `code` properties (`4001` → UserRejected,\n * `-32002` → RequestPending, `4100`/`4900`/`4901` → NotConnected:\n * unauthorized / disconnected from all-or-one chains)\n * - common message substrings: \"user rejected\" / \"user denied\",\n * \"locked\", \"chain\", etc.\n * - anything else → `Unknown` with `cause` set to the original value.\n */\nconst mapConnectionError = (raw: unknown): ConnectionError => {\n if (raw instanceof Error) {\n const message = raw.message;\n const lower = message.toLowerCase();\n\n if (message === \"Connection timeout\") {\n return { kind: \"Timeout\", message };\n }\n if (message === \"Failed to get account\" || lower.includes(\"not connected\")) {\n return { kind: \"NotConnected\", message };\n }\n\n const code = \"code\" in raw ? raw.code : undefined;\n if (code === 4001) {\n return { kind: \"UserRejected\", message };\n }\n if (code === -32_002) {\n return { kind: \"RequestPending\", message };\n }\n if (code === 4100 || code === 4900 || code === 4901) {\n return { kind: \"NotConnected\", message };\n }\n\n if (lower.includes(\"user rejected\") || lower.includes(\"user denied\")) {\n return { kind: \"UserRejected\", message };\n }\n if (lower.includes(\"locked\")) {\n return { kind: \"WalletLocked\", message };\n }\n if (lower.includes(\"chain\") && (lower.includes(\"mismatch\") || lower.includes(\"unsupported\"))) {\n return { kind: \"ChainMismatch\", message };\n }\n\n return { cause: raw, kind: \"Unknown\", message };\n }\n\n if (typeof raw === \"string\") {\n return { kind: \"Unknown\", message: raw };\n }\n\n return { cause: raw, kind: \"Unknown\", message: \"Connection failed\" };\n};\n\nexport type { ConnectionError, ConnectionErrorKind };\nexport { mapConnectionError };\n","import type { WalletPersistence } from \"../storage/persistence\";\nimport type { WalletSnapshot } from \"../storage/snapshot\";\n\nimport type { ChainBase } from \"./chain\";\nimport type { ConnectionError } from \"./errors\";\n\n/**\n * Canonical list of supported chain platforms. The single runtime source\n * of truth: `ChainPlatform` is derived from it, and storage validators\n * build their allowlists from it, so the type and the runtime checks can\n * never drift (a missing platform here was why Polkadot connections failed\n * to persist).\n */\nconst CHAIN_PLATFORMS = [\"evm\", \"svm\", \"sui\", \"bitcoin\", \"polkadot\"] as const;\n\ntype ChainPlatform = (typeof CHAIN_PLATFORMS)[number];\n\ntype Account = {\n chain: ChainBase;\n id: string;\n walletAddress: string;\n};\n\n/**\n * Build butr's `Account` shape from a wallet address and a resolved\n * `ChainBase`. The composite id (`<chain>:<address>`) is what the\n * reducer uses to compare accounts across refreshes, so every adapter\n * must build accounts through this helper (or keep the format\n * byte-identical).\n */\nconst buildAccount = (address: string, chain: ChainBase): Account => ({\n chain,\n id: `${chain.id}:${address}`,\n walletAddress: address,\n});\n\ntype Balance = {\n /** Token decimals (e.g. 9 for SOL, 18 for ETH) */\n decimals: number;\n /** Human-readable string, trimmed of trailing zeros */\n formatted: string;\n /** Token symbol (e.g. \"SOL\", \"ETH\") */\n symbol: string;\n /** Raw integer amount */\n value: bigint;\n};\n\n/**\n * Whether a wallet is currently usable from the user's environment.\n *\n * - `installed`: the wallet is available and `connect()` can be called.\n * - `loadable`: the wallet's SDK can be loaded on demand (e.g. WalletConnect\n * modal that pops a QR code without requiring a browser extension).\n * - `not-installed`: the wallet isn't reachable. Consumers typically render\n * a \"download\" affordance pointing at `meta.url`.\n */\ntype WalletAvailability = \"installed\" | \"loadable\" | \"not-installed\";\n\n/**\n * Events a connector can emit while connected. butr's runtime subscribes\n * via `Connector.subscribe?` after a successful `connect()` and dispatches\n * the equivalent reducer event:\n *\n * - `accountChanged` carries both the new active `account` AND the full\n * `accounts` array the wallet currently exposes. The runtime mirrors\n * that list verbatim into the pool entry. This handles two cases\n * uniformly:\n * - Multi-account wallets (MetaMask, Rabby, Brave): the user adds or\n * removes accounts from the dapp's permission set; the array grows\n * or shrinks to match.\n * - Single-account-exposure wallets (Phantom EVM/SVM, MetaMask Snap):\n * only the active account is ever in `accounts`; switching swaps it\n * in place rather than appending.\n * Also covers chain switches; the new chain lives inside `account.chain`.\n * - `disconnected` → `DISCONNECTED` (wallet has gone away externally:\n * user locked it, removed the extension, etc.).\n */\ntype ConnectorEvent =\n | { account: Account; accounts: Array<Account>; type: \"accountChanged\" }\n | { type: \"disconnected\" };\n\n/**\n * Capability flags describing what an adapter can actually do at\n * runtime. Populated by each adapter (the auto-built ones derive\n * these from the underlying protocol's feature advertisements;\n * hand-rolled adapters declare them explicitly). Consumers branch on\n * these to gate UI affordances:\n *\n * ```tsx\n * {wallet.connector.capabilities.requestAccounts ? (\n * <button onClick={() => requestAccounts(wallet.connector.id)}>\n * Request more accounts\n * </button>\n * ) : null}\n * ```\n *\n * Each flag means \"can this work right now,\" not \"is the method\n * defined\": `signMessage: false` means calling `signMessage()` would\n * reject; `switchChain: false` means switching is a no-op regardless\n * of which chain is passed.\n */\ntype WalletCapabilities = {\n /** `getBalance` returns a real on-chain value (vs. a 0n placeholder). */\n getBalance: boolean;\n /** `getTransactionReceipt` returns a real RPC response. */\n getTransactionReceipt: boolean;\n /** Calling `requestAccounts` will actually do something: either\n * prompt the user (EIP-2255) or refresh the exposed list. */\n requestAccounts: boolean;\n /** `sendTx` / `sendTxToChain` will work. False for SVM wallets that\n * don't advertise `solana:signAndSendTransaction`. */\n sendTransaction: boolean;\n /** `signIn` works: Sign In With Solana (`solana:signIn`). True only\n * for SVM wallets advertising the feature. */\n signIn: boolean;\n /** `signMessage` will work. False for SVM wallets that don't\n * advertise `solana:signMessage`. */\n signMessage: boolean;\n /** `signTransaction` returns a signed-but-unbroadcast transaction the\n * consumer submits with their own RPC client. True only for SVM\n * wallets advertising `solana:signTransaction`; butr ships no RPC so\n * it can't broadcast the result itself. EVM/hardware adapters leave\n * this `false` (no `signTransaction` method). */\n signTransaction: boolean;\n /** Wallet emits account/chain change events that butr can bridge. */\n subscribe: boolean;\n /** `switchAccount` is real. Almost always `false` for auto adapters;\n * neither protocol exposes silent account switch. Hand-rolled\n * adapters with custom transports may set it `true`. */\n switchAccount: boolean;\n /** `switchChain` routes subsequent calls through the new chain. EVM:\n * true via `wallet_switchEthereumChain`. SVM: true (local state +\n * per-call `chain` input) when more than one chain is advertised. */\n switchChain: boolean;\n};\n\n/**\n * Orchestration interface: what `butr` actually calls during the\n * connect / disconnect / hydrate flow. This is the contract `butr`\n * cares about; everything else on `WalletAdapter` is consumer-facing.\n */\ntype Connector<P extends ChainPlatform = ChainPlatform> = {\n /** Runtime capability flags; see `WalletCapabilities`. Read these\n * to gate UI affordances rather than probing for method existence. */\n capabilities: WalletCapabilities;\n /** Discriminant: which chain platform this adapter speaks. Generic\n * parameter `P` narrows this to a specific platform when consumers\n * use one of the per-platform adapter types (`EvmAdapter`,\n * `SvmAdapter`, etc). */\n chainPlatform: P;\n /** Begin a connection request. Resolves when the wallet is connected,\n * rejects on user cancellation or other error.\n *\n * `opts.silent` requests a non-interactive reconnect to\n * already-authorized accounts; butr's mount-time hydration passes it\n * so a reload restores wallets without re-prompting (Wallet Standard\n * `standard:connect`'s `silent` input; the `eth_accounts` read on\n * EIP-1193). Adapters that can't reconnect without a prompt should\n * reject when `silent` is set rather than show UI; hydration treats\n * the rejection as a clean restore failure. */\n connect: (opts?: { silent?: boolean }) => Promise<void>;\n /** Optional teardown. butr calls this on disconnect, error recovery, and reset. */\n disconnect?: () => Promise<void>;\n /** Read the currently-active account. butr uses this to populate the pool\n * after a successful `connect()` and during hydration. */\n getAccount: () => Promise<Account | null>;\n /** Optional. List every account the wallet exposes. Some browser wallets\n * show many accounts at once (MetaMask with multiple imports). If\n * omitted, butr defaults to `[await getAccount()]`. */\n getAccounts?: () => Promise<Array<Account>>;\n /** Optional. Wallet logo as a URL or data URI. Adapters built via butr's\n * auto-discovery (EIP-6963, Wallet Standard) populate this from the\n * wallet's announced metadata; hand-rolled adapters can leave it\n * unset and supply icons separately via `ConnectorMeta`. */\n icon?: string;\n /** Stable key: \"metamask\", \"phantom\", etc. Pool entries are keyed by this. */\n id: string;\n /** Human name: \"MetaMask\", \"Phantom\", etc. UI-facing only. */\n name: string;\n /** Optional. Ask the wallet to open its account-selection UI so the\n * user can expose additional accounts to this app. Implemented on\n * EIP-6963 wallets via `wallet_requestPermissions`; Wallet Standard\n * wallets generally leave this unset because the user enables more\n * accounts directly in the extension. Resolution doesn't include the\n * new accounts; call `getAccounts()` (or use butr's\n * `useRequestAccounts` hook, which refreshes the pool entry for\n * you). */\n requestAccounts?: () => Promise<void>;\n /** Optional. Subscribe to wallet-side events (account swap, network swap,\n * external disconnect). butr's runtime calls this after a successful\n * `connect()`, and uses the returned function to unsubscribe on\n * disconnect / reset. Bridges native wallet events into the reducer so\n * consumers don't have to wire `accountsChanged` / `chainChanged`\n * themselves. */\n subscribe?: (listener: (event: ConnectorEvent) => void) => () => void;\n};\n\n/**\n * Methods every connected wallet supports regardless of chain. The\n * per-platform `Wallet` types extend this with their platform-specific\n * methods (`signIn` for SVM, `signTransaction` for sign-only paths).\n */\ntype WalletBase = {\n /** Read a token balance. `mint` is optional; the connector decides\n * what \"no mint\" means for its chain (native ETH on EVM, native SOL\n * on Solana, etc.). */\n getBalance: (mint?: string) => Promise<Balance>;\n /** Returns a chain-specific signer. Consumers cast to the concrete\n * type via the `SignerForPlatform` registry (or directly to the\n * library shape they wrap: `WalletClient` on viem, etc.). */\n getSigner: () => Promise<unknown>;\n /** Look up the status of a previously-submitted transaction. */\n getTransactionReceipt: (tx: string) => Promise<{\n status: \"Success\" | \"Error\" | \"Pending\";\n }>;\n /** Submit a transaction on the wallet's currently-active chain.\n * Pass an `account` from `ConnectedWallet.accounts` to route the\n * transaction through a specific exposed address instead of the\n * wallet's currently-active one. EVM wallets honour this via\n * `tx.from`; Wallet Standard wallets via the feature's `account`\n * input. Omit for \"use whichever the wallet picks.\" */\n sendTx: (tx: unknown, account?: Account) => Promise<string>;\n /** Submit a transaction targeting a specific chain. The optional\n * callback fires after the connector has switched chain (consumers\n * use this to re-enable UI). Pass an `account` to route through a\n * specific exposed address (see `sendTx`). */\n sendTxToChain: (\n tx: unknown,\n targetChainId: string,\n account?: Account,\n cb?: () => void,\n ) => Promise<string>;\n /**\n * Sign a message and return both the signature and the bytes the wallet\n * actually signed. Solana Wallet Standard wallets may prefix or re-encode\n * the message internally; verifiers must check the signature against\n * `signedMessage`, not the input bytes. EVM wallets echo the input.\n *\n * Pass an `account` to sign with a specific exposed address. EIP-1193\n * routes it through `personal_sign`'s address param; Wallet Standard\n * uses the feature's `account` input. Both support per-call signing\n * without changing the wallet's active account.\n */\n signMessage: (\n msg: Uint8Array,\n account?: Account,\n ) => Promise<{ signature: Uint8Array; signedMessage: Uint8Array }>;\n /** Switch to a different account on the same wallet (some wallets\n * expose multiple accounts simultaneously). */\n switchAccount?: (address: string) => Promise<void>;\n /** Switch the wallet's active chain. */\n switchChain: (chain: ChainBase) => Promise<void>;\n};\n\n/**\n * EVM wallet surface. No `signIn` (Sign-In-With-Ethereum is an app-level\n * concern in this library, not a protocol method). No `signTransaction`:\n * EVM wallets sign-and-send via `eth_sendTransaction`; sign-only EVM\n * flows aren't exposed through this surface.\n */\ntype EvmWallet = WalletBase;\n\n/**\n * Solana wallet surface. Adds:\n * - `signIn`: Sign-In-With-Solana (`solana:signIn`). Optional;\n * `capabilities.signIn` gates availability at runtime.\n * - `signTransaction`: sign-only path for wallets that advertise\n * `solana:signTransaction` but not `solana:signAndSendTransaction`.\n * Optional; `capabilities.signTransaction` gates availability.\n */\ntype SvmWallet = WalletBase & {\n /** Sign In With Solana (SIWS, `solana:signIn`). Authenticates the user\n * and returns the connected account plus the signed statement so the\n * consumer can verify server-side. `input` is the SIWS message fields\n * (domain, statement, nonce, …); pass `{}` or omit for wallet\n * defaults. */\n signIn?: (input?: Record<string, unknown>) => Promise<{\n account: Account;\n signature: Uint8Array;\n signedMessage: Uint8Array;\n }>;\n /** Sign a Solana transaction WITHOUT broadcasting it. butr ships no\n * RPC, so the consumer broadcasts the returned bytes via\n * `@solana/kit` / `@solana/web3.js` / etc. */\n signTransaction?: (tx: unknown, account?: Account) => Promise<Uint8Array>;\n};\n\n/**\n * Sui wallet surface. Adds optional `signTransaction` for the\n * `sui:signTransaction` (sign-only) feature; broadcast is on the\n * consumer via `@mysten/sui`'s SuiClient.\n */\ntype SuiWallet = WalletBase & {\n signTransaction?: (tx: unknown, account?: Account) => Promise<Uint8Array>;\n};\n\n/**\n * Bitcoin wallet surface. `signTransaction` here is `bitcoin:signPsbt`\n * (sign-only PSBT path). Consumers pass `psbt.toBuffer()` bytes; the\n * wallet returns the signed PSBT bytes for the consumer to finalise /\n * broadcast through their own Esplora / Electrum client.\n */\ntype BitcoinWallet = WalletBase & {\n signTransaction?: (tx: unknown, account?: Account) => Promise<Uint8Array>;\n};\n\n/**\n * Polkadot/Substrate wallet surface. No standalone `signTransaction`:\n * building an extrinsic needs chain metadata (an RPC round-trip butr\n * doesn't ship), so transaction signing happens through the\n * `getSigner()` handoff; the consumer builds and submits with the\n * wallet's signer (e.g. polkadot-api). Message signing works via the\n * injected `signer.signRaw`. Same shape as `EvmWallet`.\n */\ntype PolkadotWallet = WalletBase;\n\n/** Per-platform full adapter shapes: `Connector` + the platform's\n * `Wallet` surface. These are the discriminated-union variants of\n * `WalletAdapter`. */\ntype EvmAdapter = Connector<\"evm\"> & EvmWallet;\ntype SvmAdapter = Connector<\"svm\"> & SvmWallet;\ntype SuiAdapter = Connector<\"sui\"> & SuiWallet;\ntype BitcoinAdapter = Connector<\"bitcoin\"> & BitcoinWallet;\ntype PolkadotAdapter = Connector<\"polkadot\"> & PolkadotWallet;\n\n/**\n * Full adapter interface; discriminated union by `chainPlatform`.\n *\n * Narrow on `wallet.connector.chainPlatform === \"svm\"` (etc.) to gain\n * access to platform-specific methods like `signIn` (SVM) or\n * `signTransaction` (SVM / Sui / Bitcoin). Calling those methods on a\n * non-narrowed `WalletAdapter` is a TypeScript error; that's the\n * point. The discriminant carries the type-level fact \"this method\n * doesn't exist on EVM\" so consumers can't accidentally branch on\n * `capabilities.signIn` and call a method that EVM adapters don't\n * implement.\n *\n * Runtime gating via `capabilities` still matters for the methods that\n * are OPTIONAL within a platform (a Solana wallet might or might not\n * advertise `solana:signTransaction`). Capabilities narrow \"wallet\n * supports this feature\"; the discriminated union narrows \"this\n * platform has this concept at all\".\n */\ntype WalletAdapter = EvmAdapter | SvmAdapter | SuiAdapter | BitcoinAdapter | PolkadotAdapter;\n\n/** Deprecated. Use one of the per-platform `*Wallet` types or\n * `WalletBase`. Retained as an alias so existing names resolve. */\ntype Wallet = WalletBase;\n\ntype ConnectedWallet = {\n /** Currently-active account on this wallet. */\n account: Account;\n /** All accounts known on this wallet at the time of connect/refresh.\n * Always contains at least `account`. Populated from `getAccounts()`\n * if the connector implements it; otherwise `[account]`. */\n accounts: Array<Account>;\n connector: WalletAdapter;\n};\n\ntype ConnectorMeta = {\n /** Optional. Sync probe that reports whether the wallet is currently\n * available. Defaults to `\"installed\"` when omitted. Consumers call\n * this at render time to gate the \"Connect\" button. */\n availability?: () => WalletAvailability;\n chainPlatform: ChainPlatform;\n /** Optional image URL or data URI for wallet selection UIs. */\n icon?: string;\n id: string;\n name: string;\n /** Optional. Where to send users who don't have this wallet (download\n * page, app store link, etc.). */\n url?: string;\n};\n\n/**\n * Outcome of butr's mount-time hydration pass. Passed to\n * `WalletManagerConfig.onHydrated`. Three buckets:\n *\n * - `restoredIds`: wallets that came back fully. Their pool entries\n * are live and consumers can use them immediately.\n * - `pendingIds`: wallets whose adapter wasn't registered yet\n * (auto-discovery's async warmup). The runtime retries each one\n * when discovery announces a matching id, so most of these will\n * restore within a few hundred ms of mount.\n * - `dropped`: wallets whose restore actually failed (connector\n * threw mid-flight). These have been removed from storage; consumer\n * UX can surface \"Couldn't reconnect Phantom; connect again.\"\n */\ntype HydrationOutcome = {\n dropped: Array<{ connectorId: string; reason: unknown }>;\n pendingIds: Array<string>;\n restoredIds: Array<string>;\n};\n\ntype WalletManagerConfig = {\n /** Available connector metadata */\n connectors: Array<ConnectorMeta>;\n /** Function to instantiate a connector by ID */\n createConnector: (id: string) => WalletAdapter | null;\n /**\n * Seed the store synchronously with persisted wallet state; typically\n * the return value of `readWalletSnapshot(cookies, { keyPrefix })`\n * called from a Server Component. When provided:\n * - `pool` is populated with `ConnectedWallet` entries whose\n * `connector` is a shadow adapter (see `createShadowAdapter`):\n * identity-only, all capabilities `false`, methods throw\n * `ShadowConnectorError` if called.\n * - `activeConnectorId` and `selection` are set from the snapshot.\n * - `isHydrated` flips `true` immediately on construction.\n * - Every seeded id appears in `reconnectingIds`; the background\n * silent-reconnect pass removes the id and replaces the pool\n * entry with a live adapter on success, or drops the entry on\n * failure.\n *\n * Pre-hydration UI renders from the snapshot's data (address,\n * accounts, chain, name, icon) without a flash. Action affordances\n * (sign, send) are naturally gated by the shadow's all-false\n * capabilities, or consumers can branch on `reconnectingIds`.\n */\n initialState?: WalletSnapshot;\n /** Called after a wallet is successfully connected */\n onConnect?: (wallet: ConnectedWallet) => void;\n /**\n * Called after a connection attempt fails (user rejected, wallet\n * locked, chain mismatch, timeout, …). Receives the normalised\n * `ConnectionError` plus the id of the connector that was being\n * connected. Useful for piping into observability tooling\n * (Sentry, OTel) without each consumer wiring `try/catch`s around\n * `connectWallet` themselves.\n */\n onConnectError?: (error: ConnectionError, connectorId: string) => void;\n /** Called after a wallet is disconnected */\n onDisconnect?: (chainPlatform: ChainPlatform) => void;\n /**\n * Called once after butr's mount-time hydration finishes. Receives a\n * `HydrationOutcome` summarising which stored wallets were restored,\n * which are pending an adapter announcement, and which failed.\n * Useful for surfacing \"Phantom couldn't be reconnected; try\n * again\" UX or piping a metric to telemetry.\n */\n onHydrated?: (outcome: HydrationOutcome) => void;\n /** Called after all wallets are reset (e.g., to clear auth tokens) */\n onReset?: () => void | Promise<void>;\n /**\n * Called when a connect attempt takes longer than\n * `slowConnectThresholdMs` (default 5_000) but hasn't yet resolved\n * or rejected. Fires at most once per connect attempt. Useful for\n * surfacing a \"still trying, check your wallet\" hint in the UI or\n * piping a slow-path metric to telemetry.\n */\n onSlowConnect?: (connectorId: string) => void;\n /**\n * Called when a storage write fails. butr's persistence layer is\n * fire-and-forget by design (any individual write can fail without\n * breaking butr's reducer state), but the consumer might still want\n * to know; quota-exceeded errors, IndexedDB shutdown, cross-tab\n * conflicts, cookie size limits. `context` is a short string\n * describing which write failed (e.g. `\"failed to persist pool\"`).\n * The default behaviour when no callback is set is `console.warn`.\n */\n onStorageError?: (error: unknown, context: string) => void;\n /** Threshold for `onSlowConnect`, in milliseconds. Defaults to 5_000. */\n slowConnectThresholdMs?: number;\n /** Optional custom persistence implementation (e.g., cookie-backed) */\n storage?: WalletPersistence;\n /** Storage key prefix for localStorage */\n storageKeyPrefix?: string;\n};\n\nexport { buildAccount, CHAIN_PLATFORMS };\n\nexport type {\n Account,\n Balance,\n BitcoinAdapter,\n BitcoinWallet,\n ChainPlatform,\n ConnectedWallet,\n Connector,\n ConnectorEvent,\n ConnectorMeta,\n EvmAdapter,\n EvmWallet,\n HydrationOutcome,\n PolkadotAdapter,\n PolkadotWallet,\n SuiAdapter,\n SuiWallet,\n SvmAdapter,\n SvmWallet,\n Wallet,\n WalletAdapter,\n WalletAvailability,\n WalletBase,\n WalletCapabilities,\n WalletManagerConfig,\n};\n","import type { WalletAdapter } from \"./types\";\n\n/**\n * A discovery seam. Implementations call `onAdapter(adapter)` each time\n * they find a wallet and return an unsubscribe handle. `@usebutr/wallets`\n * composes EVM + SVM into a single `WalletSource`; third parties can\n * implement this type without depending on `@usebutr/wallets`.\n */\ntype WalletSource = {\n subscribe: (onAdapter: (adapter: WalletAdapter) => void) => () => void;\n};\n\n/**\n * Wrap a bare `subscribe` function (the exact shape of\n * `discoverEvmAdapters` / `discoverSvmAdapters`) into a `WalletSource`,\n * so an EVM-only app can do\n * `createWalletSource(discoverEvmAdapters)` without importing anything\n * protocol-bearing beyond `@usebutr/evm`.\n */\nconst createWalletSource = (\n subscribe: (onAdapter: (adapter: WalletAdapter) => void) => () => void,\n): WalletSource => ({ subscribe });\n\nexport type { WalletSource };\nexport { createWalletSource };\n","import type { StoredPoolEntry } from \"../storage/persistence\";\nimport type { WalletAdapter, WalletCapabilities } from \"../types\";\n\n/**\n * Error thrown when a method is called on a shadow adapter; the\n * placeholder `WalletAdapter` that the store seeds into the pool when\n * an `initialState` is provided (e.g. from a server-rendered cookie\n * snapshot). Shadow adapters carry the identity and account data of a\n * previously-connected wallet, but the live wallet extension hasn't\n * been verified yet; the silent reconnect happens asynchronously\n * after mount.\n *\n * UI code that gates affordances on `wallet.connector.capabilities.*`\n * never reaches a shadow method (capabilities are all `false`). Code\n * that calls through anyway hits this typed error, which is the\n * correct loud failure: the consumer ignored the capability gate.\n *\n * Consumers wanting to wait out the reconnecting window should branch\n * on whether `connectorId` is in `state.reconnectingIds`.\n */\nclass ShadowConnectorError extends Error {\n // Stable programmatic identifier; consumers branch on `.code` to\n // distinguish this from generic connector errors. Read via\n // `toMatchObject({ code: \"BUTR_RECONNECTING\" })` in tests, which\n // static analysis can't trace.\n // fallow-ignore-next-line unused-class-member\n readonly code = \"BUTR_RECONNECTING\";\n readonly connectorId: string;\n readonly method: string;\n constructor(method: string, connectorId: string) {\n super(\n `[butr] ${method} called on shadow connector \"${connectorId}\". Wait for silent reconnect to complete (check reconnectingIds.has(id) before calling).`,\n );\n this.name = \"ShadowConnectorError\";\n this.connectorId = connectorId;\n this.method = method;\n }\n}\n\nconst ALL_FALSE_CAPABILITIES: WalletCapabilities = Object.freeze({\n getBalance: false,\n getTransactionReceipt: false,\n requestAccounts: false,\n sendTransaction: false,\n signIn: false,\n signMessage: false,\n signTransaction: false,\n subscribe: false,\n switchAccount: false,\n switchChain: false,\n});\n\n/**\n * Builds a placeholder `WalletAdapter` from a persisted pool entry.\n *\n * Used by `createWalletStore` when `WalletManagerConfig.initialState`\n * is provided: each stored entry becomes a `ConnectedWallet` whose\n * `connector` is one of these. The store flips `isHydrated` true\n * synchronously and exposes the data through the usual hooks\n * (`useActiveWallet`, `useConnectedWallets`, …), but the connector\n * can't actually talk to a wallet yet, so its capabilities are all\n * `false` and its methods throw `ShadowConnectorError` if called.\n *\n * The hydration coordinator's silent-reconnect pass upgrades each\n * shadow to a live `WalletAdapter` by calling `createConnector(id)`\n * (which only succeeds once the live adapter has been announced via\n * discovery or registered explicitly) and replacing the pool entry.\n * On success the connector id is removed from `reconnectingIds`; on\n * failure the entry is dropped from the pool and storage.\n *\n * The entry's `name` is required (the storage validator rejects\n * entries without it); `icon` is optional only because some live\n * adapters genuinely have no icon to begin with.\n */\nconst createShadowAdapter = (entry: StoredPoolEntry): WalletAdapter => {\n const id = entry.connectorId;\n const name = entry.name;\n const icon = entry.icon;\n\n const reject = (method: string): Promise<never> =>\n Promise.reject(new ShadowConnectorError(method, id));\n\n // Shape that satisfies the intersection of `Connector<P>` and\n // `WalletBase`. Platform-specific optional methods (`signIn`,\n // `signTransaction`) are intentionally omitted; they don't exist on\n // a shadow, and their absence is a valid runtime state for the\n // per-platform adapter types (which mark them `?:`).\n const base = {\n capabilities: ALL_FALSE_CAPABILITIES,\n connect: () => reject(\"connect\"),\n disconnect: () => reject(\"disconnect\"),\n getAccount: () => reject(\"getAccount\"),\n getBalance: () => reject(\"getBalance\"),\n getSigner: () => reject(\"getSigner\"),\n getTransactionReceipt: () => reject(\"getTransactionReceipt\"),\n icon,\n id,\n name,\n sendTx: () => reject(\"sendTx\"),\n sendTxToChain: () => reject(\"sendTxToChain\"),\n signMessage: () => reject(\"signMessage\"),\n switchChain: () => reject(\"switchChain\"),\n };\n\n switch (entry.chainPlatform) {\n case \"bitcoin\": {\n return { ...base, chainPlatform: \"bitcoin\" };\n }\n case \"evm\": {\n return { ...base, chainPlatform: \"evm\" };\n }\n case \"sui\": {\n return { ...base, chainPlatform: \"sui\" };\n }\n case \"svm\": {\n return { ...base, chainPlatform: \"svm\" };\n }\n case \"polkadot\": {\n return { ...base, chainPlatform: \"polkadot\" };\n }\n default: {\n const _exhaustive: never = entry.chainPlatform;\n void _exhaustive;\n throw new Error(`[butr] unknown chainPlatform: ${entry.chainPlatform as string}`);\n }\n }\n};\n\n/**\n * Type guard. Returns true when an adapter is a placeholder created\n * by `createShadowAdapter`. Useful for the hydration coordinator\n * (which needs to know which pool entries still need upgrading) and\n * for consumers writing wagmi-style \"is this connection verified yet\"\n * checks without subscribing to `reconnectingIds` directly.\n *\n * Detection is structural: a shadow has all capabilities set to false.\n * Live adapters always advertise at least one capability (every wallet\n * surface includes `getBalance`, `signMessage`, `switchChain` as\n * required methods, and adapter constructors set their flags\n * accordingly).\n */\nconst isShadowAdapter = (adapter: WalletAdapter): boolean => {\n // `capabilities` is a closed record of booleans, so \"every value is\n // false\" over the live object is the same check as iterating the\n // canonical `ALL_FALSE_CAPABILITIES` key set: a newly added flag is\n // forced into every adapter by the `WalletCapabilities` type.\n return Object.values(adapter.capabilities).every((flag) => !flag);\n};\n\nexport { createShadowAdapter, isShadowAdapter, ShadowConnectorError };\n","/* eslint-disable no-console -- central logging sink; the one sanctioned console use */\nconst logWarn = (...args: ReadonlyArray<unknown>): void => {\n console.warn(...args);\n};\n\nconst logError = (...args: ReadonlyArray<unknown>): void => {\n console.error(...args);\n};\n/* eslint-enable no-console */\n\nexport { logError, logWarn };\n","import type { StorageDriver } from \"./persistence\";\n\ntype BrowserStorageDrivers = {\n /** Survives app restart (localStorage on web, AsyncStorage/MMKV on RN). */\n persistent: StorageDriver;\n /** Cleared when the app session ends (sessionStorage on web, in-memory on RN). */\n session: StorageDriver;\n};\n\ntype WebStorageKind = \"localStorage\" | \"sessionStorage\";\n\nconst hasWebStorage = (kind: WebStorageKind): boolean => {\n try {\n return (\n typeof globalThis !== \"undefined\" &&\n (globalThis as Record<string, unknown>)[kind] !== undefined\n );\n } catch {\n return false;\n }\n};\n\nconst createMemoryStorageDriver = (): StorageDriver => {\n const memory = new Map<string, string>();\n return {\n getItem(key) {\n return memory.get(key) ?? null;\n },\n removeItem(key) {\n memory.delete(key);\n },\n setItem(key, value) {\n memory.set(key, value);\n },\n };\n};\n\nconst createWebStorageDriver = (kind: WebStorageKind): StorageDriver => {\n if (!hasWebStorage(kind)) {\n return createMemoryStorageDriver();\n }\n\n const storage = kind === \"localStorage\" ? globalThis.localStorage : globalThis.sessionStorage;\n\n return {\n getItem(key) {\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n },\n removeItem(key) {\n try {\n storage.removeItem(key);\n } catch {\n void 0;\n }\n },\n setItem(key, value) {\n try {\n storage.setItem(key, value);\n } catch {\n void 0;\n }\n },\n };\n};\n\n/**\n * Default storage drivers for web. `persistent` wraps `localStorage`,\n * `session` wraps `sessionStorage`. Both fall back to in-memory maps\n * when the global isn't available (SSR, non-browser environments).\n */\nconst createBrowserStorageDriver = (): BrowserStorageDrivers => ({\n persistent: createWebStorageDriver(\"localStorage\"),\n session: createWebStorageDriver(\"sessionStorage\"),\n});\n\nexport type { BrowserStorageDrivers };\nexport { createBrowserStorageDriver, createMemoryStorageDriver };\n","import { z } from \"zod\";\n\nimport { CHAIN_PLATFORMS } from \"../types/wallet\";\n\nconst chainPlatformSchema = z.enum(CHAIN_PLATFORMS);\n\nconst chainSchema = z.looseObject({\n id: z.string(),\n name: z.string(),\n namespace: z.string(),\n reference: z.string(),\n});\n\nconst accountSchema = z.looseObject({\n chain: chainSchema,\n id: z.string(),\n walletAddress: z.string(),\n});\n\nconst storedPoolEntrySchema = z.looseObject({\n account: accountSchema,\n accounts: z.array(accountSchema),\n chainPlatform: chainPlatformSchema,\n connectorId: z.string(),\n icon: z.string().optional(),\n name: z.string().min(1),\n});\n\nconst recordSchema = z.record(z.string(), z.unknown());\n\nconst parseStoredPoolEntry = (key: string, value: unknown) => {\n const parsed = storedPoolEntrySchema.safeParse(value);\n if (!parsed.success || parsed.data.connectorId !== key) {\n return null;\n }\n return parsed.data;\n};\n\nexport { chainPlatformSchema, parseStoredPoolEntry, recordSchema };\n","import { logWarn } from \"../logger\";\nimport type { ChainPlatform, ConnectedWallet } from \"../types\";\n\nimport { createBrowserStorageDriver } from \"./browser-storage-driver\";\nimport type {\n StorageDriver,\n StoredPoolEntry,\n StoredPoolRecord,\n StoredSelectionRecord,\n WalletPersistence,\n} from \"./persistence\";\nimport { chainPlatformSchema, parseStoredPoolEntry, recordSchema } from \"./validation\";\n\ntype StorageConfig = {\n keyPrefix: string;\n /** Survives app restart. Defaults to localStorage on web. */\n persistent?: StorageDriver;\n /** Cleared on session end. Defaults to sessionStorage on web. */\n session?: StorageDriver;\n};\n\nclass WalletStorage implements WalletPersistence {\n private readonly poolKey: string;\n private readonly selectionKey: string;\n private readonly activeKey: string;\n private readonly userDisconnectedKey: string;\n private readonly persistent: StorageDriver;\n private readonly session: StorageDriver;\n /**\n * Serializes pool-key mutations so concurrent fire-and-forget\n * writes can't interleave their read-modify-write phases. Without\n * this, two simultaneous `setPool` calls both read the pre-write\n * state, each merge their own entries, and whichever finishes last\n * overwrites the other's additions. Reads (`getPool`) don't enter\n * the queue; they observe whatever's currently in the driver.\n */\n private poolMutationQueue: Promise<unknown> = Promise.resolve();\n\n constructor(config: StorageConfig) {\n this.poolKey = `${config.keyPrefix}-pool`;\n this.selectionKey = `${config.keyPrefix}-selection`;\n this.activeKey = `${config.keyPrefix}-active`;\n this.userDisconnectedKey = `${config.keyPrefix}-user-disconnected`;\n\n if (config.persistent && config.session) {\n this.persistent = config.persistent;\n this.session = config.session;\n } else {\n const defaults = createBrowserStorageDriver();\n this.persistent = config.persistent ?? defaults.persistent;\n this.session = config.session ?? defaults.session;\n }\n }\n\n /** Chain `fn` after the in-flight pool mutation. */\n private async serializePoolMutation<T>(fn: () => Promise<T>): Promise<T> {\n // Capture and advance the queue synchronously so concurrent\n // callers serialize against the same head; awaiting the queue\n // first would let two callers both observe the pre-advance head\n // and run in parallel.\n const previous = this.poolMutationQueue;\n // oxlint-disable-next-line unicorn/consistent-function-scoping -- assigned by Promise constructor below\n let resolve: () => void = () => {};\n this.poolMutationQueue = new Promise<void>((r) => {\n resolve = r;\n });\n try {\n await previous;\n } catch {\n // Previous mutation's failure shouldn't jam the queue; each\n // call site already observes its own rejection.\n }\n try {\n return await fn();\n } finally {\n resolve();\n }\n }\n\n async getPool(): Promise<StoredPoolRecord> {\n try {\n const stored = await this.persistent.getItem(this.poolKey);\n if (stored === null || stored === \"\") {\n return {};\n }\n const value: unknown = JSON.parse(stored);\n const parsed = recordSchema.safeParse(value);\n if (!parsed.success) {\n await this.clearPool();\n return {};\n }\n const result: StoredPoolRecord = {};\n for (const [key, entryValue] of Object.entries(parsed.data)) {\n const entry = parseStoredPoolEntry(key, entryValue);\n if (entry === null) {\n logWarn(`[butr] dropping invalid pool entry for ${key}`);\n } else {\n result[key] = entry;\n }\n }\n return result;\n } catch (error) {\n logWarn(\"[butr] failed to parse pool from storage:\", error);\n await this.clearPool();\n return {};\n }\n }\n\n /**\n * Upsert the in-memory pool into storage. Additive: entries in\n * `pool` are written; entries already in storage that aren't in\n * `pool` are kept. The in-memory pool reflects \"what's live right\n * now\", not \"the complete list of remembered connections\"; a\n * silent reconnect that fails on reload leaves the entry out of\n * the pool but the saved entry stays so the next load can retry.\n * Use `removePoolEntry` for explicit eviction (the user clicked\n * Disconnect) and `clearAll` for a full wipe (reset).\n */\n async setPool(pool: Map<string, ConnectedWallet>): Promise<void> {\n await this.serializePoolMutation(async () => {\n try {\n const existing = await this.getPool();\n const serializable: StoredPoolRecord = { ...existing };\n for (const [connectorId, wallet] of pool) {\n const entry: StoredPoolEntry = {\n account: wallet.account,\n accounts: wallet.accounts,\n chainPlatform: wallet.connector.chainPlatform,\n connectorId,\n icon: wallet.connector.icon,\n name: wallet.connector.name,\n };\n // The runtime's reducer state is the source of truth; a\n // malformed entry here means a programming error inside butr,\n // not data drift. Throw loudly so the bug surfaces at the\n // write site rather than silently corrupting storage and\n // re-emerging as a \"wallet didn't restore\" puzzle on the next\n // page load.\n if (parseStoredPoolEntry(connectorId, entry) === null) {\n throw new Error(`[butr] refusing to persist invalid pool entry for ${connectorId}`);\n }\n serializable[connectorId] = entry;\n }\n await this.persistent.setItem(this.poolKey, JSON.stringify(serializable));\n } catch (error) {\n logWarn(\"[butr] failed to persist pool:\", error);\n }\n });\n }\n\n async removePoolEntry(connectorId: string): Promise<void> {\n await this.serializePoolMutation(async () => {\n try {\n const stored = await this.getPool();\n if (stored[connectorId]) {\n const { [connectorId]: _, ...remaining } = stored;\n await this.persistent.setItem(this.poolKey, JSON.stringify(remaining));\n }\n } catch (error) {\n logWarn(`[butr] failed to remove pool entry ${connectorId}:`, error);\n }\n });\n }\n\n async clearPool(): Promise<void> {\n await this.serializePoolMutation(async () => {\n await this.persistent.removeItem(this.poolKey);\n });\n }\n\n async getSelection(): Promise<StoredSelectionRecord> {\n try {\n const stored = await this.persistent.getItem(this.selectionKey);\n if (stored === null || stored === \"\") {\n return {};\n }\n const value: unknown = JSON.parse(stored);\n const parsed = recordSchema.safeParse(value);\n if (!parsed.success) {\n return {};\n }\n const result: StoredSelectionRecord = {};\n for (const [key, selectionValue] of Object.entries(parsed.data)) {\n const platform = chainPlatformSchema.safeParse(key);\n if (platform.success && typeof selectionValue === \"string\" && selectionValue.length > 0) {\n result[platform.data] = selectionValue;\n }\n }\n return result;\n } catch (error) {\n logWarn(\"[butr] failed to parse selection from storage:\", error);\n return {};\n }\n }\n\n async setSelection(selection: Map<ChainPlatform, string>): Promise<void> {\n try {\n const serializable: StoredSelectionRecord = {};\n for (const [platform, connectorId] of selection) {\n serializable[platform] = connectorId;\n }\n await this.persistent.setItem(this.selectionKey, JSON.stringify(serializable));\n } catch (error) {\n logWarn(\"[butr] failed to persist selection:\", error);\n }\n }\n\n async getActiveConnectorId(): Promise<string | null> {\n try {\n const value = await this.persistent.getItem(this.activeKey);\n return value !== null && value.length > 0 ? value : null;\n } catch {\n return null;\n }\n }\n\n async setActiveConnectorId(connectorId: string | null): Promise<void> {\n try {\n await (connectorId === null\n ? this.persistent.removeItem(this.activeKey)\n : this.persistent.setItem(this.activeKey, connectorId));\n } catch (error) {\n logWarn(\"[butr] failed to persist active connector id:\", error);\n }\n }\n\n async clearAll(): Promise<void> {\n // Pool removal goes through the mutation queue so it can't race\n // with an in-flight `setPool` / `removePoolEntry`. The selection\n // and active keys have no read-modify-write writers, so they can\n // remove concurrently.\n await Promise.all([\n this.clearPool(),\n this.persistent.removeItem(this.selectionKey),\n this.persistent.removeItem(this.activeKey),\n ]);\n }\n\n /**\n * Disconnect-intent tracking.\n *\n * Lives in the session driver: survives component remounts (unlike refs)\n * but clears when the session ends (unlike the persistent driver).\n * Prevents auto-connect from firing immediately after a manual disconnect,\n * while still allowing auto-connect on fresh sessions.\n */\n async isUserDisconnected(): Promise<boolean> {\n try {\n const value = await this.session.getItem(this.userDisconnectedKey);\n return value === \"true\";\n } catch {\n return false;\n }\n }\n\n async markUserDisconnected(value: boolean): Promise<void> {\n try {\n await (value\n ? this.session.setItem(this.userDisconnectedKey, \"true\")\n : this.session.removeItem(this.userDisconnectedKey));\n } catch {\n void 0;\n }\n }\n}\n\nexport { WalletStorage };\n","import { logWarn } from \"../logger\";\nimport type { Account, ChainPlatform, Connector } from \"../types\";\n\n/**\n * Side-effect callbacks the lifecycle bridge invokes when the\n * underlying wallet emits an event. The bridge owns event-to-action\n * mapping and the unsubscribe handle; the runtime owns what those\n * actions actually do (dispatch reducer events, persist, notify\n * consumer callbacks).\n */\ntype LifecycleHandlers = {\n /** Wallet exposed a new accounts list (or active account swap). The\n * bridge forwards the full array; single-account wallets included.\n * `active` is the address the wallet picked as current. */\n onAccountChanged: (\n connectorId: string,\n accounts: ReadonlyArray<Account>,\n active: Account,\n ) => void;\n /** Wallet disconnected externally (user locked, extension removed,\n * WC session ended on the relay). The bridge has already cleared\n * the subscription for `connectorId` by the time this fires. */\n onDisconnected: (connectorId: string, chainPlatform: ChainPlatform) => void;\n};\n\n/**\n * Owns the \"exactly one subscription per connector\" invariant plus the\n * event-to-handler choreography. Replaces three previously-scattered\n * call sites in the runtime (`hydrate`, `tryRestoreFromPending`,\n * `connectWallet`) and the matching teardown sites\n * (`disconnectWallet`, `reset`, the disconnect-event handler).\n */\ntype ConnectorLifecycle = {\n /**\n * Subscribe to the connector's events. Idempotent; calling `attach`\n * twice for the same `connectorId` detaches the previous subscription\n * before installing the new one, preserving the \"exactly one\"\n * invariant. No-op for connectors without a `subscribe` method.\n */\n attach: (connectorId: string, connector: Connector) => void;\n /** Detach a single connector. Safe to call when no subscription is\n * registered. */\n detach: (connectorId: string) => void;\n /** Detach every active subscription. Used during `reset`. */\n detachAll: () => void;\n};\n\nconst createConnectorLifecycle = (handlers: LifecycleHandlers): ConnectorLifecycle => {\n const unsubscribers = new Map<string, () => void>();\n\n const detach = (connectorId: string) => {\n const unsub = unsubscribers.get(connectorId);\n if (!unsub) {\n return;\n }\n try {\n unsub();\n } catch (error: unknown) {\n logWarn(\"[butr] unsubscribe threw:\", error);\n }\n unsubscribers.delete(connectorId);\n };\n\n return {\n attach: (connectorId, connector) => {\n if (!connector.subscribe) {\n return;\n }\n // Idempotent install; drop any prior subscription first so a\n // re-attach doesn't leak listeners on the wallet side.\n detach(connectorId);\n try {\n const unsub = connector.subscribe((event) => {\n switch (event.type) {\n case \"accountChanged\": {\n handlers.onAccountChanged(connectorId, event.accounts, event.account);\n break;\n }\n case \"disconnected\": {\n // Clear the subscription before notifying so the handler\n // sees a clean state and can't re-enter via dispatch\n // chains.\n detach(connectorId);\n handlers.onDisconnected(connectorId, connector.chainPlatform);\n break;\n }\n default: {\n const exhaustiveCheck: never = event;\n void exhaustiveCheck;\n }\n }\n });\n unsubscribers.set(connectorId, unsub);\n } catch (error: unknown) {\n logWarn(`[butr] subscribe failed for ${connectorId}:`, error);\n }\n },\n\n detach,\n\n detachAll: () => {\n const ids: Array<string> = [];\n for (const id of unsubscribers.keys()) {\n ids.push(id);\n }\n for (const id of ids) {\n detach(id);\n }\n },\n };\n};\n\nexport type { ConnectorLifecycle, LifecycleHandlers };\nexport { createConnectorLifecycle };\n","import type { StoredPoolEntry, WalletPersistence } from \"../storage\";\nimport { CHAIN_PLATFORMS } from \"../types\";\nimport type {\n Account,\n ChainPlatform,\n ConnectedWallet,\n Connector,\n WalletAdapter,\n WalletManagerConfig,\n} from \"../types\";\n\nconst VALID_CHAIN_PLATFORMS: ReadonlySet<string> = new Set(CHAIN_PLATFORMS);\n\nconst isChainPlatform = (value: string): value is ChainPlatform => VALID_CHAIN_PLATFORMS.has(value);\n\n/**\n * Restore outcome for a single pool entry. `kind: \"ok\"` carries the\n * fully-formed `ConnectedWallet`. `kind: \"fail\"` carries the raw error\n * so the caller can route it to telemetry.\n */\ntype RestoreOutcome =\n | { connectorId: string; entry: ConnectedWallet; kind: \"ok\" }\n | { connectorId: string; error: unknown; kind: \"fail\" };\n\n/**\n * Snapshot returned by `HydrationCoordinator.hydrate()`; everything\n * the reducer needs to compose a `HYDRATED` event plus the metadata the\n * runtime uses to wire subscriptions and surface the outcome.\n */\ntype HydrateResult = {\n activeConnectorId: string | null;\n /** Entries whose restore failed (connect() rejected, the connector\n * threw mid-flight). Reported for telemetry only; storage is\n * preserved so the next load can retry. The most common cause is\n * EIP-1193 `eth_accounts: []` from a locked wallet, which clears as\n * soon as the user unlocks and reloads. */\n dropped: Array<{ connectorId: string; reason: unknown }>;\n isUserDisconnected: boolean;\n /** Entries parked because `createConnector(id)` returned `null` at\n * hydration time (typical for Wallet Standard adapters announced\n * asynchronously). The coordinator keeps an internal record of these\n * and resolves them when the runtime later calls `drainPending`. */\n pendingIds: Array<string>;\n pool: Map<string, ConnectedWallet>;\n selection: Map<ChainPlatform, string>;\n};\n\ntype HydrationCoordinator = {\n /**\n * Restore a parked entry whose adapter has now become available.\n * Returns `null` if no entry is parked under `connectorId`. Returns an\n * `ok` outcome with the new `ConnectedWallet`, or a `fail` outcome\n * with the error (storage cleanup is handled internally).\n */\n drainPending: (connectorId: string) => Promise<RestoreOutcome | null>;\n /**\n * Read storage, instantiate every adapter that's currently\n * registered, restore in parallel, park the rest. After the returned\n * promise resolves, the coordinator holds an internal pending queue\n * indexed by `connectorId`. Resolve queued entries via `drainPending`.\n */\n hydrate: () => Promise<HydrateResult>;\n /**\n * Snapshot of currently-parked ids. The runtime uses this once\n * immediately after `hydrate()` resolves to drain entries whose\n * adapter announced *during* the hydration window (the discovery race\n * we used to resolve manually inside the store).\n */\n pendingIds: () => Array<string>;\n};\n\n/** Pick the right `accounts` list: fresh from the connector if it\n * exposes `getAccounts`, otherwise the persisted list, otherwise just\n * the active account. */\nconst resolveHydratedAccounts = async (\n connector: Connector,\n storedAccounts: ReadonlyArray<Account>,\n fallbackAccount: Account,\n): Promise<Array<Account>> => {\n if (connector.getAccounts) {\n const fresh = await connector.getAccounts().catch(() => null);\n if (fresh && fresh.length > 0) {\n return fresh;\n }\n }\n if (storedAccounts.length > 0) {\n return [...storedAccounts];\n }\n return [fallbackAccount];\n};\n\nconst restoreOneEntry = async (\n connectorId: string,\n entry: { account: Account; accounts: ReadonlyArray<Account> },\n connector: WalletAdapter,\n): Promise<RestoreOutcome> => {\n try {\n // Eager restore: ask the wallet to reconnect to already-authorized\n // accounts without prompting (Wallet Standard `silent`, EIP-1193\n // `eth_accounts`). A wallet that can't do this silently rejects;\n // the entry stays out of the pool for this session but storage is\n // preserved so the next load (e.g. once the user unlocks their\n // wallet) can retry. EIP-1193 `eth_accounts: []` is ambiguous\n // between \"locked\" and \"deauthorized\"; dropping the storage entry\n // on a transient `[]` was the cause of the reload-disconnect race.\n await connector.connect({ silent: true });\n const freshAccount = await connector.getAccount();\n const accountToUse = freshAccount ?? entry.account;\n const accounts = await resolveHydratedAccounts(connector, entry.accounts, accountToUse);\n return {\n connectorId,\n entry: {\n account: accountToUse,\n accounts,\n connector,\n },\n kind: \"ok\",\n };\n } catch (error) {\n return { connectorId, error, kind: \"fail\" };\n }\n};\n\nconst createHydrationCoordinator = (\n storage: WalletPersistence,\n createConnector: WalletManagerConfig[\"createConnector\"],\n): HydrationCoordinator => {\n const pending = new Map<string, StoredPoolEntry>();\n\n return {\n drainPending: async (connectorId) => {\n const entry = pending.get(connectorId);\n if (!entry) {\n return null;\n }\n const connector = createConnector(connectorId);\n if (!connector) {\n return null;\n }\n const outcome = await restoreOneEntry(connectorId, entry, connector);\n pending.delete(connectorId);\n return outcome;\n },\n\n hydrate: async () => {\n const [storedPool, storedSelection, storedActive, userDisconnected] = await Promise.all([\n storage.getPool(),\n storage.getSelection(),\n storage.getActiveConnectorId(),\n storage.isUserDisconnected(),\n ]);\n\n const pool = new Map<string, ConnectedWallet>();\n const dropped: Array<{ connectorId: string; reason: unknown }> = [];\n\n pending.clear();\n\n const tasks: Array<Promise<RestoreOutcome>> = [];\n for (const [connectorId, entry] of Object.entries(storedPool)) {\n if (!entry) {\n continue;\n }\n const connector = createConnector(connectorId);\n if (!connector) {\n pending.set(connectorId, entry);\n continue;\n }\n tasks.push(restoreOneEntry(connectorId, entry, connector));\n }\n\n const outcomes = await Promise.all(tasks);\n for (const outcome of outcomes) {\n if (outcome.kind === \"ok\") {\n pool.set(outcome.connectorId, outcome.entry);\n continue;\n }\n dropped.push({ connectorId: outcome.connectorId, reason: outcome.error });\n }\n\n const selection = new Map<ChainPlatform, string>();\n for (const [platform, connectorId] of Object.entries(storedSelection)) {\n if (isChainPlatform(platform) && connectorId !== undefined && pool.has(connectorId)) {\n selection.set(platform, connectorId);\n }\n }\n for (const [connectorId, wallet] of pool) {\n const platform = wallet.connector.chainPlatform;\n if (!selection.has(platform)) {\n selection.set(platform, connectorId);\n }\n }\n\n let activeConnectorId: string | null = null;\n if (storedActive !== null && pool.has(storedActive)) {\n activeConnectorId = storedActive;\n } else if (pool.size > 0) {\n activeConnectorId = pool.keys().next().value ?? null;\n }\n\n return {\n activeConnectorId,\n dropped,\n isUserDisconnected: userDisconnected,\n pendingIds: [...pending.keys()],\n pool,\n selection,\n };\n },\n\n pendingIds: () => [...pending.keys()],\n };\n};\n\nexport type { HydrateResult, HydrationCoordinator, RestoreOutcome };\nexport { createHydrationCoordinator };\n","import type { Account, ChainPlatform, ConnectedWallet } from \"../types\";\nimport type { ConnectionError } from \"../types/errors\";\n\n/**\n * Public connection-status enum. `state.connectionStatus` in the\n * reducer only takes the first four values (\"idle\" | \"connecting\" |\n * \"success\" | \"error\"); those track the user-initiated connect\n * attempt. The fifth value, `\"reconnecting\"`, is *derived* by\n * `useConnectionStatus` when the active wallet is still backed by a\n * shadow adapter (its id is in `state.reconnectingIds`). The\n * derivation lives in the React selector so the reducer can stay a\n * narrow state machine while the public API matches wagmi's\n * vocabulary.\n */\ntype ConnectionStatus = \"idle\" | \"connecting\" | \"success\" | \"error\" | \"reconnecting\";\n\ntype State = {\n activeConnectorId: string | null;\n connectingConnectorId: string | null;\n connectionError: ConnectionError | null;\n connectionStatus: ConnectionStatus;\n isHydrated: boolean;\n isUserDisconnected: boolean;\n pool: Map<string, ConnectedWallet>;\n /**\n * Connector IDs whose pool entry is currently backed by a shadow\n * adapter: created from `WalletManagerConfig.initialState` and\n * waiting for the live adapter to be announced (via discovery) and\n * the silent reconnect to succeed. The set shrinks as entries\n * upgrade (`HYDRATED` / `CONNECT_SUCCEEDED` clear matching ids) or\n * drop (`DISCONNECTED` / `RESET`). Empty for stores constructed\n * without `initialState`.\n */\n reconnectingIds: ReadonlySet<string>;\n selection: Map<ChainPlatform, string>;\n};\n\n/**\n * Lifecycle events: hydration, full reset, and the explicit\n * user-disconnected flag the runtime sets to suppress eager reconnect.\n */\ntype LifecycleEvent =\n | {\n activeConnectorId: string | null;\n isUserDisconnected: boolean;\n pool: Map<string, ConnectedWallet>;\n selection: Map<ChainPlatform, string>;\n type: \"HYDRATED\";\n }\n | { type: \"RESET\" }\n | { type: \"USER_DISCONNECTED_SET\"; value: boolean };\n\n/**\n * Connection status events: the transitions of the in-flight connect\n * attempt: start, success/failure, status/error reset. None of these\n * mutate the pool directly; `CONNECT_SUCCEEDED` is the bridge to\n * `PoolMutationEvent`.\n */\ntype ConnectionStatusEvent =\n | { connectorId: string; type: \"CONNECT_STARTED\" }\n | { connectorId: string; entry: ConnectedWallet; type: \"CONNECT_SUCCEEDED\" }\n | { error: ConnectionError; type: \"CONNECT_FAILED\" }\n | { error: ConnectionError | null; type: \"ERROR_SET\" }\n | { type: \"STATUS_RESET\" };\n\n/**\n * Pool-mutation events: changes to the set of connected wallets and\n * their per-wallet account lists. `DISCONNECTED` removes an entry;\n * the refresh events update an existing one in-place.\n */\ntype PoolMutationEvent =\n | {\n /** When set, becomes the new active account. Used by paths that\n * know which account should be active (wallet event, manual\n * update). When unset, the reducer preserves the current active\n * if it's still in `accounts`, else picks `accounts[0]`. */\n accounts: Array<Account>;\n active?: Account;\n connectorId: string;\n type: \"ACCOUNTS_REFRESHED\";\n }\n | { connectorId: string; type: \"DISCONNECTED\" }\n | { connectorId: string; type: \"WALLET_REFRESHED\" };\n\n/**\n * Selection events: which connector is active, and which connector\n * serves each chain platform. Pure pointer updates; no pool mutation.\n */\ntype SelectionEvent =\n | { chainPlatform: ChainPlatform; connectorId: string | null; type: \"SELECTION_CHANGED\" }\n | { connectorId: string | null; type: \"ACTIVE_CHANGED\" };\n\n/**\n * The single event type the reducer dispatches on. Grouped above by\n * concern so a reader sees the map before the cases; adding an event\n * means picking the group it belongs to.\n */\ntype Event = ConnectionStatusEvent | LifecycleEvent | PoolMutationEvent | SelectionEvent;\n\nconst initialState: State = {\n activeConnectorId: null,\n connectingConnectorId: null,\n connectionError: null,\n connectionStatus: \"idle\",\n isHydrated: false,\n isUserDisconnected: false,\n pool: new Map(),\n reconnectingIds: new Set(),\n selection: new Map(),\n};\n\n/** Find any connector in the pool serving a given platform. */\nconst findConnectorForPlatform = (\n pool: Map<string, ConnectedWallet>,\n chainPlatform: ChainPlatform,\n): string | undefined => {\n for (const [id, wallet] of pool) {\n if (wallet.connector.chainPlatform === chainPlatform) {\n return id;\n }\n }\n return undefined;\n};\n\n/** Pure reducer: every state transition is expressed as `(state, event) => state`.\n * No I/O, no async, no side effects. Side effects live in the runtime. */\nconst reducer = (state: State, event: Event): State => {\n switch (event.type) {\n case \"HYDRATED\": {\n const pool = new Map<string, ConnectedWallet>(state.pool);\n for (const [id, entry] of event.pool) {\n pool.set(id, entry);\n }\n const selection = new Map<ChainPlatform, string>(state.selection);\n for (const [platform, id] of event.selection) {\n selection.set(platform, id);\n }\n let activeConnectorId: string | null = null;\n if (event.activeConnectorId !== null && pool.has(event.activeConnectorId)) {\n activeConnectorId = event.activeConnectorId;\n } else if (state.activeConnectorId !== null && pool.has(state.activeConnectorId)) {\n activeConnectorId = state.activeConnectorId;\n } else if (pool.size > 0) {\n activeConnectorId = pool.keys().next().value ?? null;\n }\n let nextReconnecting: ReadonlySet<string> = state.reconnectingIds;\n if (state.reconnectingIds.size > 0 && event.pool.size > 0) {\n const next = new Set(state.reconnectingIds);\n for (const id of event.pool.keys()) {\n next.delete(id);\n }\n if (next.size !== state.reconnectingIds.size) {\n nextReconnecting = next;\n }\n }\n return {\n ...state,\n activeConnectorId,\n isHydrated: true,\n isUserDisconnected: event.isUserDisconnected,\n pool,\n reconnectingIds: nextReconnecting,\n selection,\n };\n }\n\n case \"USER_DISCONNECTED_SET\": {\n return { ...state, isUserDisconnected: event.value };\n }\n\n case \"CONNECT_STARTED\": {\n return {\n ...state,\n connectingConnectorId: event.connectorId,\n connectionError: null,\n connectionStatus: \"connecting\",\n };\n }\n\n case \"CONNECT_SUCCEEDED\": {\n const { connectorId, entry } = event;\n const existing = state.pool.get(connectorId);\n\n const nextReconnecting: ReadonlySet<string> = state.reconnectingIds.has(connectorId)\n ? new Set([...state.reconnectingIds].filter((id) => id !== connectorId))\n : state.reconnectingIds;\n\n // Same connector + same address: only flip the status, keep object refs stable\n // so reactive selectors don't churn.\n if (\n existing &&\n existing.account.walletAddress.toLowerCase() === entry.account.walletAddress.toLowerCase()\n ) {\n return {\n ...state,\n activeConnectorId: connectorId,\n connectingConnectorId: null,\n connectionStatus: \"success\",\n pool:\n // When the existing entry was a shadow, the address may\n // match but the connector reference is the placeholder.\n // Swap in the live entry so subsequent calls don't throw\n // ShadowConnectorError.\n existing.connector === entry.connector\n ? state.pool\n : new Map([...state.pool, [connectorId, entry] as const]),\n reconnectingIds: nextReconnecting,\n };\n }\n\n const newPool = new Map([...state.pool, [connectorId, entry] as const]);\n const newSelection = new Map([\n ...state.selection,\n [entry.connector.chainPlatform, connectorId] as const,\n ]);\n\n return {\n ...state,\n activeConnectorId: connectorId,\n connectingConnectorId: null,\n connectionStatus: \"success\",\n pool: newPool,\n reconnectingIds: nextReconnecting,\n selection: newSelection,\n };\n }\n\n case \"CONNECT_FAILED\": {\n return {\n ...state,\n connectingConnectorId: null,\n connectionError: event.error,\n connectionStatus: \"error\",\n };\n }\n\n case \"DISCONNECTED\": {\n const wallet = state.pool.get(event.connectorId);\n if (!wallet) {\n return state;\n }\n\n const newPool = new Map(state.pool);\n newPool.delete(event.connectorId);\n\n const newSelection = new Map(state.selection);\n const platform = wallet.connector.chainPlatform;\n if (newSelection.get(platform) === event.connectorId) {\n newSelection.delete(platform);\n const fallback = findConnectorForPlatform(newPool, platform);\n if (fallback !== undefined) {\n newSelection.set(platform, fallback);\n }\n }\n\n const firstId = newPool.keys().next();\n const activeConnectorId =\n state.activeConnectorId === event.connectorId\n ? (firstId.value ?? null)\n : state.activeConnectorId;\n\n const nextReconnecting: ReadonlySet<string> = state.reconnectingIds.has(event.connectorId)\n ? new Set([...state.reconnectingIds].filter((id) => id !== event.connectorId))\n : state.reconnectingIds;\n\n return {\n ...state,\n activeConnectorId,\n pool: newPool,\n reconnectingIds: nextReconnecting,\n selection: newSelection,\n };\n }\n\n case \"ACCOUNTS_REFRESHED\": {\n const wallet = state.pool.get(event.connectorId);\n if (!wallet) {\n return state;\n }\n // Pick the new active address. Three policies in priority order:\n // 1. Explicit `event.active` (wallet event or manual update knows\n // what should be active).\n // 2. Preserve current active if it's still in the new list.\n // 3. Fall back to `accounts[0]` so the pool entry doesn't end up\n // pointing at an address the wallet no longer exposes.\n let nextAccount: Account;\n if (event.active) {\n nextAccount = event.active;\n } else {\n const stillHasCurrent = event.accounts.some(\n (a) =>\n a.walletAddress === wallet.account.walletAddress &&\n a.chain.id === wallet.account.chain.id,\n );\n nextAccount = stillHasCurrent ? wallet.account : (event.accounts[0] ?? wallet.account);\n }\n // No-op short-circuit: when the wallet event echoes the current\n // active and the accounts array hasn't changed shape, skip the\n // Map clone so `useSyncExternalStore` subscribers don't re-render.\n // (Cheap heuristic; equality by reference for `accounts` would\n // miss content changes; we compare by length + address set.)\n const sameAccount =\n nextAccount.walletAddress === wallet.account.walletAddress &&\n nextAccount.chain.id === wallet.account.chain.id;\n const sameAccountsShape =\n event.accounts.length === wallet.accounts.length &&\n event.accounts.every((a, i) => a.walletAddress === wallet.accounts[i]?.walletAddress);\n if (sameAccount && sameAccountsShape) {\n return state;\n }\n const updated: ConnectedWallet = {\n ...wallet,\n account: nextAccount,\n accounts: [...event.accounts],\n };\n const newPool = new Map([...state.pool, [event.connectorId, updated] as const]);\n return { ...state, pool: newPool };\n }\n\n case \"WALLET_REFRESHED\": {\n const wallet = state.pool.get(event.connectorId);\n if (!wallet) {\n return state;\n }\n const newPool = new Map([...state.pool, [event.connectorId, { ...wallet }] as const]);\n return { ...state, pool: newPool };\n }\n\n case \"ACTIVE_CHANGED\": {\n return { ...state, activeConnectorId: event.connectorId };\n }\n\n case \"SELECTION_CHANGED\": {\n const newSelection = new Map(state.selection);\n if (event.connectorId === null) {\n newSelection.delete(event.chainPlatform);\n } else {\n newSelection.set(event.chainPlatform, event.connectorId);\n }\n return { ...state, selection: newSelection };\n }\n\n case \"STATUS_RESET\": {\n return {\n ...state,\n connectingConnectorId: null,\n connectionError: null,\n connectionStatus: \"idle\",\n };\n }\n\n case \"ERROR_SET\": {\n return {\n ...state,\n connectionError: event.error,\n connectionStatus: event.error ? \"error\" : \"idle\",\n };\n }\n\n case \"RESET\": {\n return {\n ...initialState,\n isHydrated: state.isHydrated,\n isUserDisconnected: true,\n reconnectingIds: new Set(),\n };\n }\n\n default: {\n const exhaustiveCheck: never = event;\n void exhaustiveCheck;\n return state;\n }\n }\n};\n\nexport type {\n ConnectionStatus,\n ConnectionStatusEvent,\n Event,\n LifecycleEvent,\n PoolMutationEvent,\n SelectionEvent,\n State,\n};\nexport { initialState, reducer };\n","/** Run an async operation fire-and-forget, calling onError if it throws. */\nconst run = async (fn: () => Promise<void>, onError: (e: unknown) => void): Promise<void> => {\n try {\n await fn();\n } catch (error) {\n onError(error);\n }\n};\n\nexport { run };\n","import { createStore } from \"zustand/vanilla\";\n\nimport { logError, logWarn } from \"../logger\";\nimport type { WalletPersistence, WalletSnapshot } from \"../storage\";\nimport { WalletStorage } from \"../storage/wallet-storage\";\nimport { CHAIN_PLATFORMS } from \"../types\";\nimport type {\n Account,\n ChainPlatform,\n ConnectedWallet,\n WalletAdapter,\n WalletManagerConfig,\n} from \"../types\";\nimport type { ConnectionError } from \"../types/errors\";\nimport { mapConnectionError } from \"../types/errors\";\n\nimport { createConnectorLifecycle } from \"./connector-lifecycle\";\nimport { createHydrationCoordinator } from \"./hydration\";\nimport { type Event, type State, initialState, reducer } from \"./reducer\";\nimport { createShadowAdapter } from \"./shadow-adapter\";\nimport { run } from \"./wallet-store-helpers\";\n\nconst VALID_CHAIN_PLATFORMS: ReadonlySet<string> = new Set(CHAIN_PLATFORMS);\n\nconst isChainPlatform = (value: string): value is ChainPlatform => VALID_CHAIN_PLATFORMS.has(value);\n\n/**\n * Build a synchronously-populated `State` from `config.initialState`.\n * Each pool entry becomes a `ConnectedWallet` whose `connector` is a\n * shadow adapter; every connector id enters `reconnectingIds` so\n * consumers can branch on \"is this connection verified\" without\n * waiting for the async silent reconnect. `isHydrated` flips true\n * synchronously: the consumer's first render sees the persisted\n * state in the live store, not undefined.\n */\nconst seedStateFromSnapshot = (snapshot: WalletSnapshot): State => {\n const pool = new Map<string, ConnectedWallet>();\n const reconnectingIds = new Set<string>();\n for (const [connectorId, entry] of Object.entries(snapshot.pool)) {\n if (!entry) {\n continue;\n }\n const connector: WalletAdapter = createShadowAdapter(entry);\n pool.set(connectorId, {\n account: entry.account,\n accounts: [...entry.accounts],\n connector,\n });\n reconnectingIds.add(connectorId);\n }\n const selection = new Map<ChainPlatform, string>();\n for (const [platform, connectorId] of Object.entries(snapshot.selection)) {\n if (isChainPlatform(platform) && connectorId !== undefined && pool.has(connectorId)) {\n selection.set(platform, connectorId);\n }\n }\n const activeConnectorId =\n snapshot.activeConnectorId !== null && pool.has(snapshot.activeConnectorId)\n ? snapshot.activeConnectorId\n : (pool.keys().next().value ?? null);\n return {\n ...initialState,\n activeConnectorId,\n isHydrated: true,\n pool,\n reconnectingIds,\n selection,\n };\n};\n\nconst CONNECT_TIMEOUT_MS = 90_000;\nconst DEFAULT_SLOW_CONNECT_THRESHOLD_MS = 5000;\n\nconst normaliseAddress = (addr: string): string => addr.toLowerCase();\n\ntype ExtractState<S> = S extends { getState: () => infer T } ? T : never;\n\ntype RuntimeMembers = {\n _config: WalletManagerConfig;\n _storage: WalletPersistence;\n connectWallet: (\n connectorId: string,\n onSuccess?: (wallet: ConnectedWallet) => void,\n onError?: (error: Error) => void,\n ) => Promise<void>;\n disconnectWallet: (connectorId: string) => void;\n getConnectorInstance: (id: string) => ReturnType<WalletManagerConfig[\"createConnector\"]>;\n hydrateWallets: () => Promise<void>;\n refreshWallet: (connectorId: string) => void;\n requestAccounts: (connectorId: string) => Promise<void>;\n reset: () => void;\n resetConnectionStatus: () => void;\n setActiveConnector: (connectorId: string | null) => void;\n setConnectionError: (error: ConnectionError | null) => void;\n setSelection: (chainPlatform: ChainPlatform, connectorId: string | null) => void;\n setUserDisconnected: (value: boolean) => void;\n tryRestoreFromPending: (connectorId: string) => Promise<void>;\n updateWalletAccount: (connectorId: string, account: Account) => void;\n};\n\ntype WalletStore = ReturnType<typeof createWalletStore>;\ntype WalletStoreState = ExtractState<WalletStore>;\n\nconst createWalletStore = (config: WalletManagerConfig) => {\n const storageKeyPrefix =\n config.storageKeyPrefix === undefined || config.storageKeyPrefix === \"\"\n ? \"butr\"\n : config.storageKeyPrefix;\n const storage = config.storage ?? new WalletStorage({ keyPrefix: storageKeyPrefix });\n\n const reportStorageError = (context: string) => (error: unknown) => {\n if (config.onStorageError) {\n try {\n config.onStorageError(error, context);\n } catch (cbError: unknown) {\n logWarn(\"[butr] onStorageError threw:\", cbError);\n }\n return;\n }\n logWarn(`[butr] ${context}:`, error);\n };\n\n // Owns the full restore lifecycle: read storage, instantiate adapters,\n // restore in parallel, park entries whose adapter wasn't registered\n // yet, drain parked entries when discovery announces a matching id.\n // `pendingRestores` lives inside the coordinator; the runtime no\n // longer manages the queue directly.\n const hydration = createHydrationCoordinator(storage, config.createConnector);\n\n return createStore<State & RuntimeMembers>()((set, get) => {\n const dispatch = (event: Event) => {\n set((prev) => reducer(prev, event), false);\n };\n\n const persistPool = (): Promise<void> =>\n run(() => storage.setPool(get().pool), reportStorageError(\"failed to persist pool\"));\n\n const persistSelection = (): Promise<void> =>\n run(\n () => storage.setSelection(get().selection),\n reportStorageError(\"failed to persist selection\"),\n );\n\n const persistActive = (): Promise<void> =>\n run(\n () => storage.setActiveConnectorId(get().activeConnectorId),\n reportStorageError(\"failed to persist active connector\"),\n );\n\n // Single entry point for \"the pool entry's exposed accounts\n // changed.\" Three call sites use it: the wallet-event bridge\n // (`accountChanged`), the consumer-facing `updateWalletAccount`\n // action, and the `requestAccounts` action. `active` is set when\n // the caller knows which address is now active (wallet event,\n // manual update); omitted when the caller just refreshed the\n // list and wants the reducer's preserve-or-fallback logic.\n const refreshPoolEntry = (connectorId: string, accounts: Array<Account>, active?: Account) => {\n dispatch({ accounts, active, connectorId, type: \"ACCOUNTS_REFRESHED\" });\n void persistPool();\n };\n\n // Owns the \"exactly one subscription per connector\" invariant,\n // the event-to-handler choreography, and the unsubscribers Map.\n // Attach is idempotent: the runtime calls it after every\n // restore / connect without first checking whether a prior\n // subscription exists.\n const lifecycle = createConnectorLifecycle({\n onAccountChanged: (connectorId, accounts, active) => {\n // Full-replace so the pool mirrors the wallet's current exposure; the wallet picks `active`.\n refreshPoolEntry(connectorId, [...accounts], active);\n },\n onDisconnected: (connectorId, chainPlatform) => {\n // Mirror an external disconnect into the reducer so the UI\n // hides the wallet, but DON'T touch storage; EIP-1193 emits\n // `accountsChanged: []` (which we forward as a `disconnected`\n // event) both when the user revokes permissions AND when\n // MetaMask simply auto-locks. The two are indistinguishable\n // from our side, so persisting the empty pool would erase the\n // saved connection on every wallet lock. Keeping storage\n // intact lets the next hydrate retry; the user-locked case\n // self-heals once they unlock and reload, and a genuine\n // revocation gets cleaned up by the next call to\n // `disconnectWallet` (or just lingers as dead bytes).\n dispatch({ connectorId, type: \"DISCONNECTED\" });\n config.onDisconnect?.(chainPlatform);\n },\n });\n\n const seeded: State = config.initialState\n ? seedStateFromSnapshot(config.initialState)\n : initialState;\n\n return {\n ...seeded,\n _config: config,\n _storage: storage,\n connectWallet: async (connectorId, onSuccess, onError) => {\n get().setUserDisconnected(false);\n\n const connector = config.createConnector(connectorId);\n if (!connector) {\n throw new Error(`Failed to create connector for ${connectorId}`);\n }\n\n dispatch({ connectorId, type: \"CONNECT_STARTED\" });\n\n // Slow-connect telemetry. Fires once if the wallet doesn't\n // resolve within the configured threshold. Cleared in finally.\n const slowThreshold = config.slowConnectThresholdMs ?? DEFAULT_SLOW_CONNECT_THRESHOLD_MS;\n const slowTimer = config.onSlowConnect\n ? setTimeout(() => {\n try {\n config.onSlowConnect?.(connectorId);\n } catch (cbError: unknown) {\n logWarn(\"[butr] onSlowConnect threw:\", cbError);\n }\n }, slowThreshold)\n : null;\n\n let connectTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n try {\n const connectPromise = connector.connect();\n // oxlint-disable-next-line promise/prefer-await-to-then -- suppress unhandled rejection; we await via Promise.race below\n void connectPromise.catch(() => {});\n await Promise.race([\n connectPromise,\n new Promise((_, reject) => {\n connectTimeoutId = setTimeout(() => {\n reject(new Error(\"Connection timeout\"));\n }, CONNECT_TIMEOUT_MS);\n }),\n ]);\n\n const account = await connector.getAccount();\n if (!account) {\n throw new Error(\"Failed to get account\");\n }\n\n const fetchedAccounts = connector.getAccounts\n ? await connector.getAccounts().catch(() => null)\n : null;\n const accounts =\n fetchedAccounts && fetchedAccounts.length > 0 ? fetchedAccounts : [account];\n\n const entry: ConnectedWallet = { account, accounts, connector };\n dispatch({ connectorId, entry, type: \"CONNECT_SUCCEEDED\" });\n\n lifecycle.attach(connectorId, connector);\n\n await Promise.all([persistPool(), persistSelection(), persistActive()]);\n\n config.onConnect?.(entry);\n onSuccess?.(entry);\n } catch (error) {\n const normalised = mapConnectionError(error);\n dispatch({ error: normalised, type: \"CONNECT_FAILED\" });\n try {\n await connector.disconnect?.();\n } catch (disconnectError: unknown) {\n logWarn(\"[butr] disconnect during error recovery failed:\", disconnectError);\n }\n try {\n config.onConnectError?.(normalised, connectorId);\n } catch (cbError: unknown) {\n logWarn(\"[butr] onConnectError threw:\", cbError);\n }\n onError?.(error instanceof Error ? error : new Error(String(error)));\n throw error;\n } finally {\n clearTimeout(connectTimeoutId);\n if (slowTimer) {\n clearTimeout(slowTimer);\n }\n }\n },\n\n disconnectWallet: (connectorId) => {\n get().setUserDisconnected(true);\n\n const state = get();\n if (!state.isHydrated) {\n return;\n }\n const wallet = state.pool.get(connectorId);\n if (!wallet) {\n return;\n }\n\n lifecycle.detach(connectorId);\n\n void run(() => wallet.connector.disconnect?.() ?? Promise.resolve(), logError);\n\n const platform = wallet.connector.chainPlatform;\n dispatch({ connectorId, type: \"DISCONNECTED\" });\n\n if (get().pool.size === 0) {\n void run(() => storage.clearAll(), reportStorageError(\"failed to clear storage\"));\n } else {\n // Explicit eviction so storage doesn't keep retrying the\n // disconnected wallet on the next load. `persistPool` is\n // additive (see `WalletStorage.setPool`), so we can't rely\n // on it to remove entries; that's what `removePoolEntry`\n // is for.\n void run(\n () => storage.removePoolEntry(connectorId),\n reportStorageError(\"failed to remove pool entry\"),\n );\n void persistSelection();\n void persistActive();\n }\n\n config.onDisconnect?.(platform);\n },\n\n getConnectorInstance: (id) => config.createConnector(id),\n\n hydrateWallets: async () => {\n const result = await hydration.hydrate();\n dispatch({\n activeConnectorId: result.activeConnectorId,\n isUserDisconnected: result.isUserDisconnected,\n pool: result.pool,\n selection: result.selection,\n type: \"HYDRATED\",\n });\n // Wire up wallet-side event subscriptions for every restored\n // connector so account/chain swaps after a refresh keep the\n // reducer in sync without consumer effort.\n for (const [connectorId, wallet] of result.pool) {\n lifecycle.attach(connectorId, wallet.connector);\n }\n await Promise.all([persistSelection(), persistActive()]);\n // Drain: catch the race where a Wallet Standard adapter\n // announced BEFORE hydration finished populating its queue.\n // Without this, the discovery callback's\n // `tryRestoreFromPending(adapter.id)` would have hit the\n // empty queue and silently returned, leaving SVM wallets\n // un-restored on reload. The coordinator's `pendingIds()`\n // is the post-hydrate snapshot; each id resolves\n // independently. Late-restore failures surface per-entry\n // inside `tryRestoreFromPending`.\n // Each restore is fire-and-forget with its own handler: one\n // rejecting restore (e.g. a throwing `createConnector`) must\n // not become an unhandled rejection, but it must still log;\n // swallowing it would hide genuine restore failures.\n for (const id of hydration.pendingIds()) {\n void run(\n () => get().tryRestoreFromPending(id),\n (e) => {\n logWarn(`[butr] late restore rejected for ${id}:`, e);\n },\n );\n }\n if (config.onHydrated) {\n try {\n config.onHydrated({\n dropped: result.dropped,\n pendingIds: [...result.pendingIds],\n restoredIds: [...result.pool.keys()],\n });\n } catch (cbError: unknown) {\n logWarn(\"[butr] onHydrated threw:\", cbError);\n }\n } else if (result.dropped.length > 0) {\n // Preserve the pre-`onHydrated` console.warn behaviour\n // when no callback is set, so silent drops still log.\n for (const { connectorId, reason } of result.dropped) {\n logWarn(`[butr] failed to restore connector ${connectorId}:`, reason);\n }\n }\n },\n refreshWallet: (connectorId) => {\n dispatch({ connectorId, type: \"WALLET_REFRESHED\" });\n },\n\n requestAccounts: async (connectorId) => {\n const entry = get().pool.get(connectorId);\n if (!entry) {\n return;\n }\n // Ask the wallet to open its picker (if supported). EVM\n // wallets honour this via `wallet_requestPermissions`;\n // Wallet Standard wallets typically have no equivalent\n // RPC, so the call resolves immediately and the refresh\n // below simply re-reads the current list.\n await entry.connector.requestAccounts?.();\n const fresh = entry.connector.getAccounts\n ? await entry.connector.getAccounts().catch(() => null)\n : null;\n if (!fresh || fresh.length === 0) {\n return;\n }\n refreshPoolEntry(connectorId, fresh);\n },\n\n reset: () => {\n get().setUserDisconnected(true);\n\n const state = get();\n if (!state.isHydrated) {\n return;\n }\n\n lifecycle.detachAll();\n\n for (const wallet of state.pool.values()) {\n void run(() => wallet.connector.disconnect?.() ?? Promise.resolve(), logError);\n }\n\n void run(() => storage.clearAll(), reportStorageError(\"failed to clear storage\"));\n\n if (config.onReset) {\n const onReset = config.onReset;\n void run(() => Promise.resolve(onReset()), logError);\n }\n\n dispatch({ type: \"RESET\" });\n },\n\n resetConnectionStatus: () => {\n dispatch({ type: \"STATUS_RESET\" });\n },\n\n setActiveConnector: (connectorId) => {\n dispatch({ connectorId, type: \"ACTIVE_CHANGED\" });\n void persistActive();\n },\n\n setConnectionError: (error) => {\n dispatch({ error, type: \"ERROR_SET\" });\n },\n\n setSelection: (chainPlatform, connectorId) => {\n dispatch({ chainPlatform, connectorId, type: \"SELECTION_CHANGED\" });\n void persistSelection();\n },\n\n setUserDisconnected: (value: boolean) => {\n dispatch({ type: \"USER_DISCONNECTED_SET\", value });\n void run(\n () => storage.markUserDisconnected(value),\n reportStorageError(\"failed to persist disconnect intent\"),\n );\n },\n\n tryRestoreFromPending: async (connectorId) => {\n // Note: deliberately NOT gating on `isUserDisconnected`.\n // The eager hydration path doesn't check that flag either;\n // stored entries restore on reload regardless of whether\n // the user's most recent action was a disconnect. The\n // late-restore path mirrors that policy for symmetry.\n const outcome = await hydration.drainPending(connectorId);\n if (!outcome) {\n return;\n }\n if (outcome.kind === \"fail\") {\n logWarn(`[butr] late restore failed for ${connectorId}:`, outcome.error);\n return;\n }\n dispatch({ connectorId, entry: outcome.entry, type: \"CONNECT_SUCCEEDED\" });\n lifecycle.attach(connectorId, outcome.entry.connector);\n await Promise.all([persistPool(), persistSelection(), persistActive()]);\n config.onConnect?.(outcome.entry);\n },\n\n updateWalletAccount: (connectorId, account) => {\n // Routes through ACCOUNTS_REFRESHED so the manual and wallet-event paths share a reducer case.\n const entry = get().pool.get(connectorId);\n if (!entry) {\n return;\n }\n const newChain = account.chain;\n const remapped = entry.accounts.map((a) =>\n a.chain.id === newChain.id\n ? a\n : {\n chain: newChain,\n id: `${newChain.id}:${normaliseAddress(a.walletAddress)}`,\n walletAddress: a.walletAddress,\n },\n );\n const seen = remapped.some(\n (a) => normaliseAddress(a.walletAddress) === normaliseAddress(account.walletAddress),\n );\n const accounts = seen ? remapped : [...remapped, account];\n refreshPoolEntry(connectorId, accounts, account);\n },\n };\n });\n};\n\nexport type { WalletStore, WalletStoreState };\nexport { createWalletStore };\n","import type { StorageDriver } from \"./persistence\";\n\ntype InitialCookies = Iterable<[string, string]> | Readonly<Record<string, string>>;\n\ntype CookieDriverOptions = {\n /**\n * Cookie `domain` attribute. Omit to scope to the current host.\n * Set to a parent domain (e.g. `.example.com`) to share state\n * across subdomains.\n */\n domain?: string;\n /**\n * Snapshot of cookies for the SSR pass; typically the result of\n * Next.js' `cookies()` (from `next/headers`) or a parsed\n * `req.headers.cookie`. Used only when `document` is unavailable.\n *\n * When provided, `getItem` reads from this snapshot during the\n * server render so the store sees the same persisted state the\n * client will see after hydration. Writes remain no-ops on the\n * server: emitting `Set-Cookie` has to be done by the framework\n * layer that owns the response.\n */\n initialCookies?: InitialCookies;\n /**\n * Lifetime in seconds. Defaults to 30 days. Pass `undefined`\n * (the default) for \"until the session ends\", but note that\n * butr persists wallet state across sessions, so a finite\n * max-age is usually what consumers want.\n */\n maxAgeSeconds?: number;\n /**\n * URL path the cookie applies to. Defaults to `/` (whole origin).\n */\n path?: string;\n /**\n * `SameSite` attribute. Defaults to `\"lax\"`; restrictive enough\n * to avoid CSRF on cross-origin POSTs, permissive enough for\n * top-level navigations.\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n /**\n * `Secure` attribute. Defaults to `true` (cookies only sent over\n * HTTPS). Force `false` for local development on plain `http://`.\n */\n secure?: boolean;\n};\n\nconst DEFAULT_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;\n\nconst encode = (value: string): string => encodeURIComponent(value);\nconst decode = (value: string): string => decodeURIComponent(value);\n\nconst readCookies = (): Map<string, string> => {\n const out = new Map<string, string>();\n if (typeof document === \"undefined\") {\n return out;\n }\n const cookieString = document.cookie;\n if (!cookieString) {\n return out;\n }\n for (const segment of cookieString.split(\";\")) {\n const trimmed = segment.trim();\n if (!trimmed) {\n continue;\n }\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const name = trimmed.slice(0, eq);\n const raw = trimmed.slice(eq + 1);\n try {\n out.set(name, decode(raw));\n } catch {\n void 0;\n }\n }\n return out;\n};\n\nconst buildCookieString = (\n name: string,\n value: string,\n options: CookieDriverOptions,\n expired = false,\n): string => {\n const parts: Array<string> = [`${name}=${encode(value)}`, `Path=${options.path ?? \"/\"}`];\n if (options.domain !== undefined && options.domain !== \"\") {\n parts.push(`Domain=${options.domain}`);\n }\n if (expired) {\n parts.push(\"Max-Age=0\");\n } else {\n const maxAge = options.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;\n parts.push(`Max-Age=${maxAge}`);\n }\n parts.push(`SameSite=${options.sameSite ?? \"lax\"}`);\n if (options.secure ?? true) {\n parts.push(\"Secure\");\n }\n return parts.join(\"; \");\n};\n\nconst toCookieMap = (input: InitialCookies | undefined): Map<string, string> | null => {\n if (!input) {\n return null;\n }\n if (Symbol.iterator in input) {\n return new Map(input);\n }\n return new Map(Object.entries(input));\n};\n\n/**\n * Cookie-backed storage driver. Reads/writes `document.cookie`;\n * server-readable, survives reloads, scoped per `domain`/`path`.\n *\n * **When to use this:** SSR apps that need to know who's connected\n * during the server render (so they can stream the connected-wallet\n * UI without a client-side hydration flicker). Pass `initialCookies`\n * from a server-side cookie source (e.g. `cookies()` in Next.js'\n * `next/headers`, or a parsed `req.headers.cookie`) and the same\n * driver will serve those values during the server render and switch\n * to `document.cookie` once it mounts in the browser.\n *\n * **Trade-offs vs `localStorage`:** cookies travel with every\n * request, so they cost bytes on the wire. Keep the storage key\n * prefix short, and prefer this driver for the `persistent` slot\n * only: the `session` slot can stay in `sessionStorage` (which\n * cookies can't natively model anyway).\n *\n * **Server-side writes are no-ops.** Emitting `Set-Cookie` requires\n * access to the framework's response object, which a storage driver\n * shouldn't reach into. The store doesn't mutate persisted state\n * during the SSR pass anyway; writes only fire after client mount,\n * once `document.cookie` is reachable.\n */\nconst createCookieStorageDriver = (options: CookieDriverOptions = {}): StorageDriver => {\n const seeded = toCookieMap(options.initialCookies);\n\n if (typeof document === \"undefined\") {\n if (!seeded) {\n return {\n getItem() {\n return null;\n },\n removeItem() {},\n setItem() {},\n };\n }\n return {\n getItem(key) {\n return seeded.get(key) ?? null;\n },\n removeItem() {},\n setItem() {},\n };\n }\n return {\n getItem(key) {\n return readCookies().get(key) ?? null;\n },\n removeItem(key) {\n // eslint-disable-next-line unicorn/no-document-cookie -- cookie storage driver is the document.cookie abstraction by design\n document.cookie = buildCookieString(key, \"\", options, true);\n },\n setItem(key, value) {\n // eslint-disable-next-line unicorn/no-document-cookie -- cookie storage driver is the document.cookie abstraction by design\n document.cookie = buildCookieString(key, value, options);\n },\n };\n};\n\nexport type { CookieDriverOptions, InitialCookies };\nexport { createCookieStorageDriver };\n","import { logWarn } from \"../logger\";\n\nimport type { StoredPoolRecord, StoredSelectionRecord } from \"./persistence\";\nimport { chainPlatformSchema, parseStoredPoolEntry, recordSchema } from \"./validation\";\n\n/**\n * Server-safe view of a butr-persisted session; everything you can\n * know about a user's connected wallets from the cookie payload alone,\n * without instantiating a `Connector`.\n *\n * Notably absent: the `Connector` instance. A wallet extension exists\n * only in the browser, so a server render can know *which* wallet was\n * connected and *what address* it held, but cannot dispatch\n * `signMessage`/`sendTransaction` on it. Splitting display from action\n * along this seam keeps the impossibility expressed in the types\n * rather than hidden inside a runtime check.\n */\ntype WalletSnapshot = {\n activeConnectorId: string | null;\n pool: StoredPoolRecord;\n selection: StoredSelectionRecord;\n};\n\ntype CookieSource =\n | Iterable<{ name: string; value: string }>\n | Iterable<[string, string]>\n | Readonly<Record<string, string>>;\n\ntype SnapshotOptions = {\n /**\n * Same prefix passed to `WalletManagerProvider` / `WalletStorage`.\n * Defaults to `\"butr\"` to match the library default.\n */\n keyPrefix?: string;\n};\n\nconst EMPTY_SNAPSHOT: WalletSnapshot = Object.freeze({\n activeConnectorId: null,\n pool: Object.freeze({}) as StoredPoolRecord,\n selection: Object.freeze({}) as StoredSelectionRecord,\n});\n\nconst toCookieMap = (input: CookieSource): Map<string, string> => {\n if (!(Symbol.iterator in input)) {\n return new Map(Object.entries(input));\n }\n const out = new Map<string, string>();\n for (const entry of input) {\n if (Array.isArray(entry)) {\n const [name, value] = entry;\n if (typeof name === \"string\" && typeof value === \"string\") {\n out.set(name, value);\n }\n continue;\n }\n if (typeof entry.name === \"string\" && typeof entry.value === \"string\") {\n out.set(entry.name, entry.value);\n }\n }\n return out;\n};\n\nconst parsePool = (raw: string | undefined): StoredPoolRecord => {\n if (raw === undefined || raw === \"\") {\n return {};\n }\n try {\n const value: unknown = JSON.parse(raw);\n const parsed = recordSchema.safeParse(value);\n if (!parsed.success) {\n return {};\n }\n const result: StoredPoolRecord = {};\n for (const [key, entryValue] of Object.entries(parsed.data)) {\n const entry = parseStoredPoolEntry(key, entryValue);\n if (entry === null) {\n logWarn(`[butr] readWalletSnapshot: dropping invalid pool entry for ${key}`);\n } else {\n result[key] = entry;\n }\n }\n return result;\n } catch (error) {\n logWarn(\"[butr] readWalletSnapshot: failed to parse pool cookie:\", error);\n return {};\n }\n};\n\nconst parseSelection = (raw: string | undefined): StoredSelectionRecord => {\n if (raw === undefined || raw === \"\") {\n return {};\n }\n try {\n const value: unknown = JSON.parse(raw);\n const parsed = recordSchema.safeParse(value);\n if (!parsed.success) {\n return {};\n }\n const result: StoredSelectionRecord = {};\n for (const [key, selectionValue] of Object.entries(parsed.data)) {\n const platform = chainPlatformSchema.safeParse(key);\n if (platform.success && typeof selectionValue === \"string\" && selectionValue.length > 0) {\n result[platform.data] = selectionValue;\n }\n }\n return result;\n } catch (error) {\n logWarn(\"[butr] readWalletSnapshot: failed to parse selection cookie:\", error);\n return {};\n }\n};\n\n/**\n * Parse a cookie source into a server-safe `WalletSnapshot`.\n *\n * Pure, sync, no `document`, no React; runnable in any environment\n * (Server Component, route handler, edge middleware, even client\n * code). Pair with `createCookieStorageDriver({ initialCookies })`\n * and `<WalletManagerProvider initialSnapshot={…} />` to render a\n * connected shell server-side without a hydration flash.\n *\n * **Stale-snapshot semantics.** The snapshot reflects whatever the\n * browser most recently persisted. If the user has since uninstalled\n * the wallet, switched accounts, or disconnected in another tab, the\n * client-side hydration will reconcile reality and the live store\n * will diverge from the snapshot. Treat the snapshot as an\n * *optimistic* shell; accurate enough to avoid a paint flicker,\n * authoritative only after `useIsHydrated()` is true.\n *\n * **Inputs.** Accepts the three shapes Next.js / Express / Hono /\n * generic-Node cookie code naturally produces:\n * - A plain object: `{ \"butr-pool\": \"{...}\", … }`\n * - An array of `{ name, value }` (Next.js' `cookies().getAll()`)\n * - An iterable of `[name, value]` tuples\n *\n * Malformed entries are dropped with a `logWarn` (same policy as\n * `WalletStorage.getPool`); a cross-tab corruption shouldn't crash\n * the server render.\n */\nconst readWalletSnapshot = (\n source: CookieSource,\n options: SnapshotOptions = {},\n): WalletSnapshot => {\n const keyPrefix =\n options.keyPrefix === undefined || options.keyPrefix === \"\" ? \"butr\" : options.keyPrefix;\n const cookies = toCookieMap(source);\n\n const pool = parsePool(cookies.get(`${keyPrefix}-pool`));\n const selection = parseSelection(cookies.get(`${keyPrefix}-selection`));\n\n const rawActive = cookies.get(`${keyPrefix}-active`);\n let activeConnectorId: string | null = null;\n if (rawActive !== undefined && rawActive.length > 0 && pool[rawActive] !== undefined) {\n activeConnectorId = rawActive;\n } else {\n // Mirror `HydrationCoordinator.hydrate` selection-fallback: when no\n // explicit active is stored, surface any pool member so the render\n // shell can still show \"connected\" instead of \"disconnected\".\n const firstKey = Object.keys(pool)[0];\n if (firstKey) {\n activeConnectorId = firstKey;\n }\n }\n\n return { activeConnectorId, pool, selection };\n};\n\nexport type { CookieSource, SnapshotOptions, WalletSnapshot };\nexport { EMPTY_SNAPSHOT, readWalletSnapshot };\n","import type { ConnectedWallet } from \"./types\";\n\n/**\n * Two wallet snapshots are equivalent for selector purposes iff they\n * share the same adapter instance, active account address, and active\n * account chain id. Used by `useStoreWithEqualityFn` consumers\n * (active-wallet, selected-wallet, useWalletEntry) to suppress spurious\n * re-renders when the underlying Map churns but the resolved entry\n * hasn't changed.\n *\n * The adapter is compared by reference, not by `connector.id`: hydration\n * replaces a shadow adapter with the live one under an unchanged id and\n * address, so an id comparison reports \"equal\" and leaves consumers\n * holding a placeholder whose every method throws ShadowConnectorError.\n *\n * Hoisted to its own module so the equivalence rule lives in one place;\n * if we ever extend the snapshot (e.g. to consider `accounts.length`),\n * every selector hook picks up the new rule for free.\n */\nconst walletEqual = (a: ConnectedWallet | undefined, b: ConnectedWallet | undefined): boolean => {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n return (\n a.connector === b.connector &&\n a.account.walletAddress === b.account.walletAddress &&\n a.account.chain.id === b.account.chain.id\n );\n};\n\nexport { walletEqual };\n","/**\n * Normalize a wallet-announced icon string.\n *\n * Wallets announce their icon through external metadata; EIP-6963\n * `providerInfo.icon`, Wallet Standard `wallet.icon`. That value is\n * not under butr's control, and some wallets ship data-URI icons with\n * surrounding whitespace (a newline left over from a pretty-printed\n * manifest). Strict consumers reject it: Next.js's `<Image>` throws\n * because `src` must not start with a control character.\n *\n * Trims surrounding whitespace and treats an all-whitespace (or empty)\n * icon as absent, so consumers get either a usable string or\n * `undefined`: never a blank or malformed one. `undefined` passes\n * through untouched.\n */\nconst sanitizeIcon = (icon: string | undefined): string | undefined => {\n if (icon === undefined) {\n return undefined;\n }\n const trimmed = icon.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n};\n\nexport { sanitizeIcon };\n","/**\n * Shared byte-encoding helpers for the connector packages.\n *\n * These functions sit directly on the signing/address path of every\n * chain. They used to be hand-reimplemented in ~10 connector files; a\n * single tested module removes the drift surface (a `padStart` omission\n * or base64 variant mismatch corrupts signatures/addresses for one chain\n * only, and the divergence is invisible because the copies look \"the\n * same\").\n *\n * Hex prefixing diverges across chains, so the module exposes **explicit\n * variants** rather than one function:\n * - {@link bytesToHex} returns bare hex (Bitcoin, Ledger).\n * - {@link bytesToHexPrefixed} returns `0x`-prefixed hex (EVM, Polkadot).\n * - {@link hexToBytes} tolerantly strips an optional `0x` (all callers).\n */\n\n/** Bare lowercase hex, no `0x` prefix (Bitcoin, Ledger). */\nconst bytesToHex = (bytes: Uint8Array): string => {\n let hex = \"\";\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, \"0\");\n }\n return hex;\n};\n\n/** `0x`-prefixed lowercase hex (EVM, Polkadot). */\nconst bytesToHexPrefixed = (bytes: Uint8Array): string => `0x${bytesToHex(bytes)}`;\n\n/**\n * Decode hex (with or without a leading `0x`) into raw bytes. Throws on\n * odd-length input or non-hex characters rather than silently producing\n * `NaN`-filled bytes.\n */\nconst hexToBytes = (hex: string): Uint8Array => {\n const clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n if (clean.length % 2 !== 0) {\n throw new TypeError(\"Invalid hex: odd length\");\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i += 1) {\n const byte = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(byte)) {\n throw new TypeError(`Invalid hex character at offset ${i * 2}`);\n }\n out[i] = byte;\n }\n return out;\n};\n\n/**\n * Cross-platform base64 → `Uint8Array`. `atob` is available everywhere\n * butr runs (browsers, RN since Hermes, Node 16+, Bun, Deno).\n */\nconst base64ToBytes = (b64: string): Uint8Array => {\n const binary = atob(b64);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n out[i] = binary.codePointAt(i) ?? 0;\n }\n return out;\n};\n\n/** Cross-platform `Uint8Array` → base64. */\nconst bytesToBase64 = (bytes: Uint8Array): string => {\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCodePoint(byte);\n }\n return btoa(binary);\n};\n\nexport { base64ToBytes, bytesToBase64, bytesToHex, bytesToHexPrefixed, hexToBytes };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,yBAAyB,aAA0D;CACvF,SAAS,QAAQ,WAAW,CAAC;CAC7B,KAAK,QAAQ,OAA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